1

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);
    }}
  />
)
Furkan Öztürk
  • 441
  • 4
  • 21
  • 1
    useState is executed async. If you want to use the latest value you should use useEffect. [Here it's explained][1] [1]: https://dev.to/shareef/react-usestate-hook-is-asynchronous-1hia – LadyHail Feb 22 '23 at 11:18

1 Answers1

3

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]);
Adilius
  • 308
  • 2
  • 10