Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

242
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda