Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda