Reputation: 21
I have following methods under API_SERVICE.
export const API_SERVICE = {
post: post,
get: get,
put: put,
patch: patch
};
Export above method from API_SERVICE.
So IF I want to post I'll call like:
API_SERVICE.post(url , data) / API_SERVICE.patch(url , data)
Here my question is I have one form for both update and create. Both function are same. I want to reuse this code.
How to call this methods dynamically ?
Below showing error:
[isEdit ? API_SERVICE.patch : API_SERVICE.post]( url , data ).then(response => ....
Error: (intermediate value)] is not a function
Upvotes: 0
Views: 789
Reputation:
If you want to call It dynamically in return statement you have to use curly braces so it should look something like this:
{ isEdit ? ApiService.patch(url, data) : ApiService.post(url, data) }
I don't think that you can use then() inside {} so your function Should be async and do it's job by it self, change some state for example Regards Adrian
Upvotes: 0
Reputation: 1214
You should change the method in another way let me give an example:
const req = await fetch(url,{
method : isEdit ? 'PUT' : 'POST',
body: JSON.stringfy(data),
headers: {
"Content-Type": "application/json"
}
})
Upvotes: 0
Reputation: 515
I think this is not a question about React, but a question about JavaScript.
In JavaScript, you can call methods in this way:
const foo = num => num + 1;
const bar = num => num * 2;
(true ? foo : bar)(2);
// get 3
(false ? foo : bar)(2);
// get 4
This might achieve what you are expected.
Upvotes: 1