Home > database >  Weird behavior with setState in React: State never saving
Weird behavior with setState in React: State never saving

Time:01-31

I have a project where I need to capture all user inputs and concat all characters into a string state variable. My current code can capture all inputs, however the state variable is always one char. Ex: User types "a" and state is set to "A". Then user types "b", and state is set to "B". Intended behavior is state to be set to "AB".

Current code:

const [currentGuess, setCurrentGuess] = useState<string>("");
useEffect(() => {
    const listener = (e: KeyboardEvent) => {
        if (e.code === "Enter") {
            console.log("Pressed enter");
        } else if (e.code === "Backspace") {
            console.log("Pressed backspace");
        } else {
            const key = e.key.toUpperCase();
            if (key.length === 1 && key >= "A" && key <= "Z") {
                setCurrentGuess(`${currentGuess}${key}`);
            }
        }
    };
    window.addEventListener("keyup", listener);
    return () => {
        window.removeEventListener("keyup", listener);
    };
}, []);

CodePudding user response:

Since currentGuess doesn't change in the listener's scope, just change the set:

...
setCurrentGuess((previousGuess) => `${previousGuess}${key}`);
...

this will allow to use the previously set guess.


More on this here.

  •  Tags:  
  • Related