Skip to content
Advertisement

Multiple useState in if statement

I’m trying to make a small tennis match simulator.

And so far everytime a player reach actualScore: 4 I would like to update my player useState and add +1 to their setWon, however it never update it and I don’t get why. The block of code:

    if (playerOneData.actualScore >= 4) {
      setPlayerOneData({ ...playerOneData, setWon: playerOneData.setWon + 1 })
      setPlayerOneData({ ...playerOneData, actualScore: 0 })
      setPlayerTwoData({ ...playerTwoData, actualScore: 0 })

    }

All the code:

function App() {

  const [playerOneData, setPlayerOneData] = useState({
    name: "blabla",
    level: 2,
    setWon: 0,
    actualScore: 0,
  })

  const [playerTwoData, setPlayerTwoData] = useState({
    name: "blabla",
    level: 4,
    setWon: 0,
    actualScore: 0,
  })

  const generateRandomBall = () => {
    let random = Math.floor(Math.random() * 101);
    console.log(random);
    if (playerOneData.actualScore >= 4) {
      setPlayerOneData({ ...playerOneData, setWon: playerOneData.setWon + 1 })
      setPlayerOneData({ ...playerOneData, actualScore: 0 })
      setPlayerTwoData({ ...playerTwoData, actualScore: 0 })

    }
    else if (playerTwoData.actualScore >= 4) {
      setPlayerTwoData({ ...playerTwoData, setWon: playerTwoData.setWon + 1 })
      setPlayerTwoData({ ...playerTwoData, actualScore: 0 })
      setPlayerOneData({ ...playerOneData, actualScore: 0 })

    }
    else if (random > 50) {
      setPlayerOneData({ ...playerOneData, actualScore: playerOneData.actualScore + 1 })

    }
    else if (random <= 50) {
      setPlayerTwoData({ ...playerTwoData, actualScore: playerTwoData.actualScore + 1 })
    }
  }

Advertisement

Answer

  1. useState is an asynchronus operation. So when you are trying to call multiple setState at the same time the execution is messed up.

  2. also you will need to set the data based on the previous data.

Here is how the code should be modified

setPlayerTwoData(prevData => {
  return {
    ...prevData,
    actualScore: 0,
    setWon: prevData.setWon + 1
})

and the updates should work correctly

Advertisement