Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
Dynamic Function in React

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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"
 }
})
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!