Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading