0

I am working on a Memory Game Project in React. I have an array of pokemon objects (since I use those as input for the game) and I set the nextPokemon in state to be an object at a random index in said pokemonsArray. Afterwards, I am adding the nextPokemon to an array called renderedPokemon, which I map over in the render function and create a button for every one of them. Now I already found out that if I have multiple state setters in one place, they get batched together and therefore it makes sense for my renderedPokemon array to receive an empty object when I add nextPokemon to it, because nextPokemon hasn't been evaluated yet. I added my code at the bottom, because I still have issues with a lot of it, which is:

a) understanding why setNextPokemon doesn't work, because it is the first process in line and doesn't even rely on previously set state, therefore batching it together with other state setters shouldn't be an issue

b) getting to know how updater functions help me since in setRenderedPokemon, using for example "prev => prev + x" doesn't help - I don't rely on previous values from the same state but from another state

You can see the code below. Any help is be appreciated.

    const [pokemonsArray, setPokemonArray] = useState(pokemons);
    const [score, setScore] = useState(0);
    const [renderedPokemon, setRenderedPokemon] = useState([]);
    const [nextPokemon, setNextPokemon] = useState({});

    useEffect(() => {
         for (let i = 0; i < 9; i++) {
              if (score === 49) {
                 return
              } else if (renderedPokemon.length == 0) {
                        setNextPokemon(pokemonsArray[Math.floor(Math.random() * 49)]);
                        setRenderedPokemon(nextPokemon);
              }
         }
    }
skyboyer
  • 22,209
  • 7
  • 57
  • 64
  • Before trying to debug this, keep in mind that all setState calls are asynchronous. – Dimitar Jun 29 '22 at 11:40
  • When you call `setRenderedPokemon`, `nextPokemon` hasn't been updated yet. Fortunately, you know the value you're updating it to already, so you can use that value instead. – David Jun 29 '22 at 11:44
  • @David How would the syntax for adding that updated value to setRenderedPokemon instead look like? – Gianluca Jahn Jun 29 '22 at 11:50
  • @GianlucaJahn: It would be the same syntax any time you want to pass the same value to two different functions. Store the new value for `nextPokemon` in a variable. Pass that variable to `setNextPokemon`. Pass that variable to `setRenderedPokemon`. – David Jun 29 '22 at 11:52

0 Answers0