Home > Back-end >  Dynamic Function in React
Dynamic Function in React

Time:01-06

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

CodePudding user response:

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.

CodePudding user response:

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"
 }
})

CodePudding user response:

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

  •  Tags:  
  • Related