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

175
Visualizações
How to write react code with settimeout correctly?

I have the next code:

const Button = () => {
  const [numbers, setNumbers] = useState({
    a: 10,
    b: 30,
    c: 100,
    d: new Date()
  });

  const click = () => {
    setTimeout(click2, 2000);
  };

  const click2 = () => {
    setNumbers({
      a: numbers.a + 1,
      b: numbers.b + 1,
      c: numbers.c + 1,
      d: new Date()
    });
  };

  return (
    <>
      <button onClick={click}>+</button>
      <p>{numbers.a}</p>
      <p>{numbers.b}</p>
      <p>{numbers.c}</p>
      <p>{numbers.d.toLocaleString()}</p>
    </>
  );
};

When I press the button once, the code works correctly. But if I press the button twice in a row, the code will only run once. Please explain why this is happening and how to make the code run every time you click it?

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

0

It's because click2 function will have the old state value itself when clicked the second time as the setState of the first click is not run yet, Instead of referencing statevalue directly use prevState method of setting state, according to that change your click2 function as below

    setNumbers((num) => {
      return {
        a: num.a + 1,
        b: num.b + 1,
        c: num.c + 1,
        d: new Date()
      };
    });
  };

Please refer this codesandbox for reference

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