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);
}
}
}