@@ -11,14 +11,11 @@ const defaults: Options = {
1111
1212const useKeyPress = ( targetKey : string , config : Options = defaults ) => {
1313 const [ state , setState ] = useState ( false ) ;
14- const { useKeyboardJS } = config ;
15-
16- let keyboardjs ;
14+ const [ keyboardjs , setKeyboardJs ] = useState < any > ( null ) ;
15+ const { useKeyboardJS} = config ;
1716
1817 if ( useKeyboardJS ) {
19- import ( "keyboardjs" ) . then ( module => {
20- keyboardjs = module ;
21- } ) ;
18+ import ( "keyboardjs" ) . then ( setKeyboardJs ) ;
2219 }
2320
2421 const regularDownHandler = ( { key } : KeyboardEvent ) => {
@@ -42,20 +39,24 @@ const useKeyPress = (targetKey: string, config: Options = defaults) => {
4239
4340 useEffect ( ( ) => {
4441 if ( useKeyboardJS ) {
45- keyboardjs . bind ( targetKey , customDownHandler , customUpHandler ) ;
42+ if ( keyboardjs ) {
43+ keyboardjs . bind ( targetKey , customDownHandler , customUpHandler ) ;
44+ }
4645 } else {
4746 window . addEventListener ( "keydown" , regularDownHandler ) ;
4847 window . addEventListener ( "keyup" , regularUpHandler ) ;
4948 }
5049 return ( ) => {
5150 if ( useKeyboardJS ) {
52- keyboardjs . unbind ( targetKey , customDownHandler , customUpHandler ) ;
51+ if ( keyboardjs ) {
52+ keyboardjs . unbind ( targetKey , customDownHandler , customUpHandler ) ;
53+ }
5354 } else {
5455 window . removeEventListener ( "keydown" , regularDownHandler ) ;
5556 window . removeEventListener ( "keyup" , regularUpHandler ) ;
5657 }
5758 } ;
58- } , [ targetKey , useKeyPress ] ) ;
59+ } , [ targetKey , useKeyPress , keyboardjs ] ) ;
5960
6061 return state ;
6162} ;
0 commit comments