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

229
Visualizações
How do I switch states(useState) through key event listeners (ReactJS)

I am trying to flip a card on space bar. It flips once but does not flip back. I'm flipping the card through a true, false useState and JS keydown event handler. I have an example below that recreates the same problem without all of the other jargon in my original code. It changes to "true" from false after I press space as intended. However, it does not switch back.

Should I be doing this differently? How would you go about this?

    import React from "react";
    import { useEffect, useState } from "react";

    export const Test = () => {
      const [isOn, setIsOn] = useState(false);

      const handleKeyPress = (e) => {
        if (e.key === " ") {
          console.log(isOn);
          onFlip();
        }
      };

      const onFlip = () => {
        setIsOn(!isOn);
      };

      useEffect(() => {
        setIsOn(false);
        document.addEventListener("keydown", handleKeyPress);
        return () => document.removeEventListener("keydown", handleKeyPress);
      }, []);
      return <p>{isOn.toString()}</p>;
    };


<!-- language: lang-html -->

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can do this:

import { useEffect, useState } from "react";

export default function App() {
  const [isOn, setIsOn] = useState(false);

  useEffect(() => {
    const handleKeyPress = (e) => {
      if (e.key === " ") {
        setIsOn((prevState) => !prevState);
      }
    };

    document.addEventListener("keydown", handleKeyPress);
    return () => document.removeEventListener("keydown", handleKeyPress);
  }, []);

  return <p>{isOn.toString()}</p>;
}

Basically, I pass all the logic to the useEffect, so he don't have any dependency. Also have add this setIsOn((prevState) => !prevState);, this is the best away to update the opposite value of the state.

Some links to explain: https://stackoverflow.com/a/48394541/12816782

about 4 years ago · Juan Pablo Isaza Relatório

0

Why its not working is because you are trying to get the updated state inside the function which is called from document.addEventListener. the function that gets called from document.addEventListener never gets the updated state so every time value of isOn is false inside onFlip function. You can use the useRef functionality to achieve your requirement.

 import React from "react";
import { useEffect, useState, useRef } from "react";

export const Test = () => {
  const [isOn, SetIsOn] = useState(false);
  const isOnRef = useRef(false);

  const handleKeyPress = (e) => {
    if (e.key === " ") {
      console.log(isOn);
      onFlip();
    }
  };

  const onFlip = () => {
    isOnRef.current = !isOnRef.current;
    SetIsOn(!isOnRef.current);
};

  useEffect(() => {
    SetIsOn(false);
    document.addEventListener("keydown", handleKeyPress);
    return () => document.removeEventListener("keydown", handleKeyPress);
  }, []);
  return <p>{isOn.toString()}</p>;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

I have added the following line to your code

  1. const isOnRef = useRef(false);
  2. changed the onFlip function.
about 4 years ago · Juan Pablo Isaza Relatório

0

You should put isOn on useEffect's dependencies. register event listener should be unregiste / register each time isOn is changed, because isOn used on function onFlip need to up to date. Try this:

useEffect(() => {
    SetIsOn(false);
}, []);

useEffect(() => {
    document.addEventListener("keydown", handleKeyPress);
    return () => document.removeEventListener("keydown", handleKeyPress);
}, [isOn]);
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