I’ve set a handleClick function that should update the state of my variable when called, and it does, but I also need the displayed variable to update on-screen from the same click. It was working earlier, but has since stopped, no idea what I changed because I’ve yet to learn version control (my bad.)
This is the code in question.
import React, {useState} from 'react';
import Numbergen from './Numbergen.js';
import Comparenums from './Comparenums.js';
const Guessbox = () => {
const [userInput, setUserInput] = useState(0);
const [guess, setGuess] = useState(userInput)
const [numToGuess, setNumToGuess] = useState(Numbergen());
const [result, setResult] = useState('')
const handleChange = (event) => {
setUserInput(event.target.value);
};
const handleClick = () => {
setGuess(userInput);
setResult(Comparenums(guess,numToGuess));
}
return (
<div>
<input
type="text"
id="userInput"
name="userInput"
onChange={handleChange}
value={userInput}
/>
<button onClick={handleClick}>Guess!</button>
<h2>{result}</h2>
<h2>{numToGuess}</h2>
</div>
);
}
export default Guessbox;
I’m very new at all this, so I apologize for any faux pas in my post.
I’ve tried adding this.
to my useState variables because I saw that worked for some other people in similar situations, kind of hoping for a hail marry on that one. I also tried calling handleClick twice in the same onClick, expecting it might call it twice to both set and update the variable onscreen, it did not do that.
2
Answers
SOLUTION 1
You don’t have to create another state. When you crate another state with its initial value then it needs to be updated.
It will initially updated with
0
and when you update it in
handleChange
then it will update in next tick and you are comparing it will last updated value which won’t be right. Just create a single state and no need to update it just compare it with that value after convert it into number.Working solution
SOLUTION 2
For any reason let say you want to compare it with
guess
then you have to updateguess
whenuserInput
changes, so that when you click on theguess
button then on then time of comparisonguess
state would have updated: