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

useState Array is always 1 step behind

I’m trying to update an array using react’s useState, however it is always 1 step behind.
I made a minimal reproduction using here:
Edit sad-worker-9xv7dq
Surely I’m misunderstanding how useState works as the onChange value triggers correctly.

export default Home(){
  const [inputData, setInputData] = useState<{ exercise: string; weight: number }[]>([]);
  function procesWeightInput(exercise: string, weight: number) {
    const input = { exercise, weight };
    setInputData([input]);
    console.log(inputData);
  }

return (         
    <input
    type="number"
    placeholder="Weight"
    onChange={(e) => {
      console.log("The value", e.target.value);
      procesWeightInput(exercise.name, +e.target.value);
    }}
  />
)

>Solution :

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

useState hook is asynchronous which makes the setInputData update the inputData value after the console.log() call

See this StackOverflow answer: https://stackoverflow.com/a/54069332/7916220

If you add a useEffect hook you can console.log() the value once it is updated even if the update hook is asynchronous. Update your code with a useEffect hook it should properly console.log() the inputData value.

import { useState, useEffect } from "react";

  useEffect(() => {
    console.log(inputData);
  }, [inputData]);
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