Skip to content

Commit

Permalink
Merge pull request #110 from streamich/fix-keyboardjs
Browse files Browse the repository at this point in the history
fix: πŸ› better async loading for keyboardjs
  • Loading branch information
streamich authored Feb 19, 2019
2 parents 72867fd + 2096bae commit e795f6e
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 e795f6e

Please sign in to comment.