Home > Software engineering >  ReactJS state array pushing issues
ReactJS state array pushing issues

Time:11-08

I have an array in a react state hook. I'm pushing values to it in a way that i assumed was the correct way, yet the array is always empty when i try to log it. What about my method of pushing to the array is not correct?

const [betHistory, setBetHistory] = useState([""]);

Inside my function (which i've tested is being called, and betCount is never blank)

function placeBet() {
  console.log(betCount);
  setBetHistory(betHistory => [...betHistory, betCount.toString()]);
  console.log(betHistory);
}

The log is always blank.

CodePudding user response:

Setting the state will update the value on the next render, not immediately. If you need to access the updated value right away, store it in a variable:

function placeBet() {
  const newBetHistory = [...betHistory, betCount.toString()];
  setBetHistory(newBetHistory);
  console.log(newBetHistory);
}
  • Related