Skip to content

Commit

Permalink
fix: πŸ› better async loading for keyboardjs
Browse files Browse the repository at this point in the history
closes #103
  • Loading branch information
streamich committed Feb 19, 2019
1 parent 72867fd commit 2096bae
Showing 1 changed file with 10 additions and 9 deletions.
19 changes: 10 additions & 9 deletions src/useKeyPress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,11 @@ const defaults: Options = {

const useKeyPress = (targetKey: string, config: Options = defaults) => {
const [state, setState] = useState(false);
const { useKeyboardJS } = config;

let keyboardjs;
const [keyboardjs, setKeyboardJs] = useState<any>(null);
const {useKeyboardJS} = config;

if (useKeyboardJS) {
import("keyboardjs").then(module => {
keyboardjs = module;
});
import("keyboardjs").then(setKeyboardJs);
}

const regularDownHandler = ({ key }: KeyboardEvent) => {
Expand All @@ -42,20 +39,24 @@ const useKeyPress = (targetKey: string, config: Options = defaults) => {

useEffect(() => {
if (useKeyboardJS) {
keyboardjs.bind(targetKey, customDownHandler, customUpHandler);
if (keyboardjs) {
keyboardjs.bind(targetKey, customDownHandler, customUpHandler);
}
} else {
window.addEventListener("keydown", regularDownHandler);
window.addEventListener("keyup", regularUpHandler);
}
return () => {
if (useKeyboardJS) {
keyboardjs.unbind(targetKey, customDownHandler, customUpHandler);
if (keyboardjs) {
keyboardjs.unbind(targetKey, customDownHandler, customUpHandler);
}
} else {
window.removeEventListener("keydown", regularDownHandler);
window.removeEventListener("keyup", regularUpHandler);
}
};
}, [targetKey, useKeyPress]);
}, [targetKey, useKeyPress, keyboardjs]);

return state;
};
Expand Down

0 comments on commit 2096bae

Please sign in to comment.