I have a API post method in my react app. I need to add or remove a parameter inside the body conditionally
If the variable 'locale' value is 'all'.I don't need locale inside body of post method. If the 'locale' is not 'all' then I need to attach locale inside the post method.
I used if else..just wanted to know if there is a better way to handle this. This is just a overview (pseudo code) of my code.
If(locale?.includes('all')) {
return API.post(),{
body: {
id,
status
}}}
else{
return API.post(),{
body: {
id,
status,
locale
}}}
CodePudding user response:
you can use below. I prefer to write code like this .
let body = {
id : id,
status : status
}
if(locale==="all"){
body = {
...body,
locale:locale
}
return API.post(body);
CodePudding user response:
You could use something like this.
let body = { id, status };
if(!locale?.includes("all")){
body = { ...body, locale };
}
return API.post(body);