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