Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
State not setting correctly when Enter is pressed

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:

enter image description here

However, when I press Enter and when I console.log the current attempt, I don't see anything:

enter image description here

...and of course nothing gets added to the stored attempts array (or maybe an empty string gets added). What am I doing wrong?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!