From 2096bae65b72b92576dfccc948af4e110540fe1c Mon Sep 17 00:00:00 2001 From: streamich Date: Tue, 19 Feb 2019 17:18:10 +0100 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=90=9B=20better=20async=20loading?= =?UTF-8?q?=20for=20keyboardjs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit closes #103 --- src/useKeyPress.ts | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/useKeyPress.ts b/src/useKeyPress.ts index b708135bbe..958c643dd6 100644 --- a/src/useKeyPress.ts +++ b/src/useKeyPress.ts @@ -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(null); + const {useKeyboardJS} = config; if (useKeyboardJS) { - import("keyboardjs").then(module => { - keyboardjs = module; - }); + import("keyboardjs").then(setKeyboardJs); } const regularDownHandler = ({ key }: KeyboardEvent) => { @@ -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; };