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

Access the updated value after Set state in React

The component renders the sum , which was calculated by previous values.

I know how batches work and why is this. I could solve this by implementing a button and connect the button to a click event handler , but I would like to calculate the sum with onChange Event inside the calculate() funciton .

So I would like to handle the set state and the calculation process in the same function.

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

So my quiestion is how could I get the updated value of num1 and num2 , which was updated in the same batch:

setSum(parseFloat(**Updated**num1) + parseFloat(**Updated**num2))

export default function Home() {
  const [num1 , SetNum1] = useState(0.0)
  const [num2 , setNum2] = useState(0.0)
  const [sum, setSum] = useState(0.0)


  const calculate = (e) => {
    switch(e.target.id){
      case 'num1':
        SetNum1((prev) => {
          return e.target.value
        })
        break;
      case 'num2':
        setNum2((prev) => {
          return e.target.value
        })
        break;
    }
    setSum(parseFloat(num1) + parseFloat(num2))
  }

  return (
    <div>
      <form>
        <input type="number" className="form-control"  id="num1" value={num1} onChange={(e) => calculate(e)}  />
        <input type="number" className="form-control"  id="num2" value={num2} onChange={(e) => calculate(e)}  />
        Sum : {sum}
      </form>
    </div>
  )
}

Is it possible to access the most recent num1 value after SetNum1 or I have to implement a button which calculates the sum?

>Solution :

You want to listen for changes with useEffect.

export default function Home() {
  const [num1 , setNum1] = useState(0.0)
  const [num2 , setNum2] = useState(0.0)
  const [sum, setSum] = useState(0.0)


  // execute the function whe num1 or num2 is changed
  useEffect(() => {
    setSum(parseFloat(num1) + parseFloat(num2))
  }, [num1, num2]);

  return (
    <div>
      <form>
        <input type="number" className="form-control"  id="num1" value={num1} onChange={(e) => setNum1(e.target.value)}  />
        <input type="number" className="form-control"  id="num2" value={num2} onChange={(e) => setNum2(e.target.value)}  />
        Sum : {sum}
      </form>
    </div>
  )
}
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