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

92
Visualizações
How to setState and immiediately invoke it within the same function?

I'm writing a function that simultaneously sets state AND assigns it to an object.. I'm specifically talking about setValue and after: value

    const handleAddToHistory = (e) => {
    e.preventDefault();
    
    setValue((parseFloat(Object.values(data))*fromTo).toFixed(2))
    
    setHistory([ ... history , {
      date: new Date().toISOString().slice(0, 10),
      before: fromTo,
      after: value,
    }])
  }

However, on the first run "value" is empty. It forces me to click the button again, and only then it shows all the data properly.

How can I setState and immiediately invoke it ? Should I do some sort of Time Interval on setHistory to wait until setValue is actually set?

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

0

When you set state in React, it's asynchronous, since it triggers a re-render. Therefore, you use useEffect to handle anything that needs to happen when value changes:

    useEffect(() => {
      setHistory([ ... history , {
          date: new Date().toISOString().slice(0, 10),
          before: fromTo,
          after: value,
       }])
    }, [value])
about 4 years ago · Juan Pablo Isaza Relatório

0

Any reason to not do this?

    const handleAddToHistory = (e) => {
    e.preventDefault();
    
    const valueToSave = (parseFloat(Object.values(data))*fromTo).toFixed(2);
    setValue(valueToSave)
    
    setHistory([ ... history , {
      date: new Date().toISOString().slice(0, 10),
      before: fromTo,
      after: valueToSave,
    }])
  }

If that doesn't work for some reason, you can use a useEffect hook:

  const handleAddToHistory = (e) => {
    e.preventDefault();
    
    setValue(parseFloat(Object.values(data))*fromTo).toFixed(2))
  }
  useEffect(() => {
    setHistory([ ... history , {
      date: new Date().toISOString().slice(0, 10),
      before: fromTo,
      after: value,
    }]);
  }, [value]);
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