@@ -11,14 +11,11 @@ const defaults: Options = {
11
11
12
12
const useKeyPress = ( targetKey : string , config : Options = defaults ) => {
13
13
const [ state , setState ] = useState ( false ) ;
14
- const { useKeyboardJS } = config ;
15
-
16
- let keyboardjs ;
14
+ const [ keyboardjs , setKeyboardJs ] = useState < any > ( null ) ;
15
+ const { useKeyboardJS} = config ;
17
16
18
17
if ( useKeyboardJS ) {
19
- import ( "keyboardjs" ) . then ( module => {
20
- keyboardjs = module ;
21
- } ) ;
18
+ import ( "keyboardjs" ) . then ( setKeyboardJs ) ;
22
19
}
23
20
24
21
const regularDownHandler = ( { key } : KeyboardEvent ) => {
@@ -42,20 +39,24 @@ const useKeyPress = (targetKey: string, config: Options = defaults) => {
42
39
43
40
useEffect ( ( ) => {
44
41
if ( useKeyboardJS ) {
45
- keyboardjs . bind ( targetKey , customDownHandler , customUpHandler ) ;
42
+ if ( keyboardjs ) {
43
+ keyboardjs . bind ( targetKey , customDownHandler , customUpHandler ) ;
44
+ }
46
45
} else {
47
46
window . addEventListener ( "keydown" , regularDownHandler ) ;
48
47
window . addEventListener ( "keyup" , regularUpHandler ) ;
49
48
}
50
49
return ( ) => {
51
50
if ( useKeyboardJS ) {
52
- keyboardjs . unbind ( targetKey , customDownHandler , customUpHandler ) ;
51
+ if ( keyboardjs ) {
52
+ keyboardjs . unbind ( targetKey , customDownHandler , customUpHandler ) ;
53
+ }
53
54
} else {
54
55
window . removeEventListener ( "keydown" , regularDownHandler ) ;
55
56
window . removeEventListener ( "keyup" , regularUpHandler ) ;
56
57
}
57
58
} ;
58
- } , [ targetKey , useKeyPress ] ) ;
59
+ } , [ targetKey , useKeyPress , keyboardjs ] ) ;
59
60
60
61
return state ;
61
62
} ;
0 commit comments