Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Weird behavior with setState in React: State never saving

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);
    };
}, []);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading