The whole idea of the component is that the first time the Escape key is pressed, the value confirm in state changes to true to verify that the user really wants to execute the secPress() function and pressing the Escape key again within 5 seconds run the secPress() function.
Unfortunately, the secPress() function in the component never run.
How to get the function to run after the second key press?
import React, { useState, useEffect, useCallback } from "react";
export function useKeypress(key, action) {
useEffect(() => {
function onKeyup(e) {
if (e.key === key) action();
}
window.addEventListener("keyup", onKeyup);
return () => window.removeEventListener("keyup", onKeyup);
}, []);
}
const App = () => {
const [confirm, setConfirm] = useState(false);
// this function never run
const secPress = () => {
console.log("Double escape pressed");
};
const _confirm = useCallback(() => {
setConfirm((prev) => !prev);
console.log(confirm); // <-- always show false
if (confirm) {
secPress();
}
}, [confirm]);
useKeypress("Escape", _confirm);
useEffect(() => {
const d = setTimeout(() => {
setConfirm(false);
}, 5000);
return () => {
clearTimeout(d);
};
}, [confirm]);
return <>{confirm ? "true" : "false"}</>;
};
export default App;
React version: 17.0.2