Advertisements
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:
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 :
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]);