So I’m working on a portfolio piece. It’s a pokemon math game and I have the intergers generating with math random but when I set the hook for the answer to the problem interger it calcuates it one step back from the actual problem. So if the page loads with 12 + 2 and the level medium is selected the math problem will change to lets say 5 – 5 but the problemAnswer is going to be 14 not 0.
const [answer, setAnswer] = useState("");
const [randomInt, setRandomInt] = useState(null);
const [randomIntTwo, setRandomIntTwo] = useState(null);
const [problemAnswer, setProblemAnswer] = useState(null);
useEffect(() => {
setRandomInt(Math.floor(Math.random() * (12 - 1 + 1) + 1));
setRandomIntTwo(Math.floor(Math.random() * (12 - 1 + 1) + 1));
if (difficulty === 1) {
setProblemAnswer(randomInt + randomIntTwo);
} else if (difficulty === 2) {
setProblemAnswer(randomInt - randomIntTwo);
} else if (difficulty === 3) {
setProblemAnswer(randomInt * randomIntTwo);
}
console.log(randomInt, randomIntTwo);
}, [difficulty, selectedPokemon]);
I used useEffect to set the random number and calculate them.
function handleSubmitAnswer(e) {
e.preventDefault();
console.log(randomInt, randomIntTwo);
setAnswer(e.target.value);
//console.log(problemAnswer);
//console.log(answer);
if (answer === problemAnswer) {
setCorrect(true);
}
setResponse(true);
setTimeout(() => {
setResponse(false);
}, 3500);
setAnswer("");
if (stage === 1 && answer === problemAnswer) {
setSelectedPokemon(stagetwo[selectedPokemon.id - 1]);
setAnswer("");
setStage(2);
} else if (stage === 2 && answer === problemAnswer) {
setStage(3);
setSelectedPokemon(stagethree[selectedPokemon.id - 1]);
setAnswer("");
}
}
>Solution :
React states behave like snapshots. You are accessing the old value at the time the current render begins. The new values set in this render are applied in the next render.
You can save the new values in local variables to fix it:
useEffect(() => {
const newRandom = Math.floor(Math.random() * 12 + 1);
const newRandomTwo = Math.floor(Math.random() * 12 + 1);
setRandomInt(newRandom);
setRandomIntTwo(newRandomTwo);
if (difficulty === 1) {
setProblemAnswer(newRandom + newRandomTwo);
} else if (difficulty === 2) {
setProblemAnswer(newRandom - newRandomTwo);
} else if (difficulty === 3) {
setProblemAnswer(newRandom * newRandomTwo);
}
}, [difficulty, selectedPokemon]);
Learn more at State as a Snapshot – React.