I'm making an app in React which should be similar to the "Wordle" game. In the initial version it should listen to key events, print out letters and when Enter is pressed it should store the current attempt and print it out as well. For the current attempt I'm using array of characters. When Enter is pressed, my idea is to join that array thus converting it to a single string and to add that to another array of stored attempts. Here's my code:
import { useEffect, useState } from "react";
const Board = () => {
const [currentAttempt, setCurrentAttempt] = useState([]);
const [storedAttempts, setStoredAttempts] = useState([]);
useEffect(() => {
const onLetterTyped = (e) => {
// Accept only letters
if (e.keyCode >= 65 && e.keyCode <= 90) {
setCurrentAttempt((prevState) => [...prevState, e.key]);
}
// Enter
if (e.keyCode === 13) {
console.log("Current attempt: " + currentAttempt);
setStoredAttempts((prevState) => [
...prevState,
currentAttempt.join(""),
]);
setCurrentAttempt([]);
}
};
window.addEventListener("keyup", onLetterTyped);
return () => {
window.removeEventListener("keyup", onLetterTyped);
};
}, []);
return (
<div>
<p>{currentAttempt}</p>
<div>
{storedAttempts.map((word, i) => (
<div key={i}>{word}</div>
))}
</div>
</div>
);
};
export default Board;
While I'm typing letters (for example 'h', 'e', 'l', 'l', 'o'), everything renders nicely in the document:
However, when I press Enter and when I console.log the current attempt, I don't see anything:
...and of course nothing gets added to the stored attempts array (or maybe an empty string gets added). What am I doing wrong?
You're defining onLetterTyped within the effect which is likely causing the issue. You should define it in the component instead (next to state definitions) and only add the event listeners in the effect:
import { useEffect, useState } from "react";
const Board = () => {
const [currentAttempt, setCurrentAttempt] = useState([]);
const [storedAttempts, setStoredAttempts] = useState([]);
const onLetterTyped = (e) => {
// Accept only letters
if (e.keyCode >= 65 && e.keyCode <= 90) {
setCurrentAttempt((prevState) => [...prevState, e.key]);
}
// Enter
if (e.keyCode === 13) {
console.log("Current attempt: " + currentAttempt);
setStoredAttempts((prevState) => [
...prevState,
currentAttempt.join(""),
]);
setCurrentAttempt([]);
}
};
useEffect(() => {
window.addEventListener("keyup", onLetterTyped);
return () => {
window.removeEventListener("keyup", onLetterTyped);
};
}, []);
return (
<div>
<p>{currentAttempt}</p>
<div>
{storedAttempts.map((word, i) => (
<div key={i}>{word}</div>
))}
</div>
</div>
);
};
export default Board;