Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

241
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda