const [numbers, setNumbers] = ({number1: 2, number2:0})
const [aNumber, setNumber] = (1);
useEffect(()=>{
},[numbers,aNumber])
const printNumbers = ()=>{
setNumbers({...numbers, number2:aNumber});
console.log(numbers);
}
return (
<>
<button onClick={printNumbers}>print a number <button/>
</>
)
when i click on the button in the console it will print {number1: 2, number2: 0} But i want it to print {number1: 2, number2: 1} but it looks like react not update mi hook correrctly, but... when a click another time in the button it prints {number1: 2, number2: 1}, but i need it in the first click, how can i fix it?
CodePudding user response:
You set the console log inside the printNumbers function. Since the state update is async, you'd have to put the console.log inside the useEffect to be notified after an update. Something similar to:
useEffect(()=>{
console.log(numbers);
},[numbers,aNumber])
const [numbers, setNumbers] = ({number1: 2, number2:0})
const [aNumber, setNumber] = (1);
const printNumbers = ()=>{
setNumbers({...numbers, number2:aNumber});
}
CodePudding user response:
In React, state updates are asynchronous and batched. setState
is not guaranteed to run (and in practice, new values will never be available) before the proceeding code. To solve this, use a local variable to retain a copy of the new state which you can both dispatch with your setState
, and log immediately:
const printNumbers = () => {
const newNumbers = { ...numbers, number2: aNumber };
setNumbers(newNumbers);
console.log(newNumbers);
}