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

111
Visualizações
Function runs two to three times

I have a function in my react app that capitalized the first letter of a word or string that is fetched from an API:

  // Capitalize the first letter of the word/phrase
  const capitalize = (string) => {
    if (string) {
      return string
        .toLowerCase()
        .split(" ")
        .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
        .join(" ");
    } else {
      return;
    }
  };

Note: string is the text that is being fetched from the API. I call the function like so:

capitalize(userInfo.address)

It works as expected but upon logging the results to the console, I realized that it is being run two to three times.

Sandbox: https://codesandbox.io/s/admiring-bose-2qr01j?file=/src/App.js

Is there a way to fix this?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This might be caused by React Strict Mode. Check your index.js. By default React wraps your <App/> component with <React.StrictMode> which intentionally invokes the render method of your inner components two times.

root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

Just remove it to run functions only once.

root.render(
  <App />
);
about 4 years ago · Juan Pablo Isaza Relatório

0

It seems that the function is correct, but perhaps, when it is executed after a call to an external data source, an asynchronous call is being made (and possibly more than one), so the capitalize function is executed more than once .

Try to make the function run regardless of where you are calling from.

It could also be that you are executing the function from a code block that is executed more than once, because the function seems to be correct and does not have anything iterative.

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