Toggling works with useEffect
but doesn't work with useHotKeys
#704
-
I have a state in import { proxy, useSnapshot } from "valtio";
class State {
commandPalette: boolean = false;
toggleCommandPalette = () => {
state.commandPalette = !state.commandPalette;
};
}
export const state = proxy(new State());
export const useStore = () => useSnapshot(state); My working code using React.useEffect(() => {
const onKeyDown = (e: KeyboardEvent) => {
if ((e.key === 'k' && e.metaKey) || e.ctrlKey) {
state.toggleCommandPalette()
}
}
window.addEventListener('keydown', onKeyDown)
return () => {
window.removeEventListener('keydown', onKeyDown)
}
}, []) The below code using useHotkeys(
"command+k, ctrl+k",
() => {
state.toggleCommandPalette();
},
[]
); It works for 1st toggle when I press ⌘K the first time but after that first time, it doesn't work. The same code works with Reproduction → https://codesandbox.io/s/combobox-bug-ypm9g6?file=/src/Search.tsx Uncomment the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
That is because the input in your popup is receiving focus when it gets displays. Keyboard events are ignored in useHotkeys(
"command+k, ctrl+k",
() => {
state.toggleCommandPalette();
},
{
enableOnTags: ["INPUT"]
}
); Codesanbox: https://codesandbox.io/s/combobox-bug-forked-6rdzqh |
Beta Was this translation helpful? Give feedback.
That is because the input in your popup is receiving focus when it gets displays. Keyboard events are ignored in
useHotkeys
unless you define the form tags you want it to listen to. If you enable hotkeys for input tags it works fine:Codesanbox: https://codesandbox.io/s/combobox-bug-forked-6rdzqh