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>