const [key, setKey] = useState<string | null>(null);
const pointerLocation = useRef(0);
useEffect(() => {
console.count("key listener");
const handleKeyDown = (e: KeyboardEvent) => {
setKey(e.key);
};
window.addEventListener("keydown", handleKeyDown);
return () => {
window.removeEventListener("keydown", handleKeyDown);
};
}, [key]);
useEffect(() => {
const letter = document.getElementsByClassName("letter");
if (key) {
if (letter[pointerLocation.current] && key.length === 1) {
letter[pointerLocation.current].textContent = key;
pointerLocation.current++;
}
}
if (key === "Backspace") {
if (letter[pointerLocation.current - 1]) {
letter[pointerLocation.current - 1].textContent = "";
pointerLocation.current--;
}
}
}, [key, pointerLocation]);
The second useEffect hook only runs when the key state value changes, even if the new value is the same as the previous one. This means that if a user presses the same key twice, the second useEffect hook won't run again, and the text won't update as expected.
I tried to change the dependency array of the second useEffect hook to include the pointerLocation variable as well, hoping that the effect would be triggered whenever either key or pointerLocation changes. However, this did not work since the pointerLocation variable is not being updated anywhere in the component.
I also tried to add a random number to the key state variable whenever it is updated to the same value, hoping that it would trigger the effect. However, this caused unnecessary re-renders and was not an optimal solution.