Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

209
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda