0
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?

  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Brian Thompson Feb 17 '22 at 20:28

2 Answers2

1

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});
}
YVK.
  • 48
  • 4
  • And if i want to do a fetch sending the numbers when i clic, i have to make te fetch into te useEffect? because the numbers ill sending into printNumbers are not updated. –  Feb 17 '22 at 19:58
  • It depends on what you want to do. If you are fetching data when you open your app, you can create a useEffect to work as a ComponentDidMounte, giving to this one an empty array as a second param. But if you want to fetch data just when you click you can use this fetch inside printNumbers, use setNumbers with the fetch response and it will work just fine, if you use a async await with the fetch. If it's not clear, or if i got your question wrong, just post it here and I'll take a look and see if I can help! – YVK. Feb 18 '22 at 01:19
0

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);
}
tobiasfried
  • 1,689
  • 8
  • 19