1- import { useEffect , useRef , useState } from 'react' ;
1+ import { useCallback , useEffect , useRef , useState } from 'react' ;
22import usePrevious from './hooks/use-previous' ;
33import { useAppState } from './hooks/use-app-state' ;
44import Killswitch from './killswitch' ;
@@ -8,7 +8,7 @@ interface UseKillswitchOptions {
88 androidApiKey : string ;
99 language : string ;
1010 version : string ;
11- apiHost ? : string ;
11+ apiHost : string ;
1212 useNativeUI ?: boolean ;
1313 timeout ?: number ;
1414}
@@ -18,23 +18,35 @@ export function useKillswitch({
1818 androidApiKey,
1919 language,
2020 version,
21- apiHost = 'https://killswitch.mirego.com' ,
21+ apiHost,
2222 useNativeUI = true ,
2323 timeout = 2000 ,
2424} : UseKillswitchOptions ) {
25- const killswitch = useRef (
26- new Killswitch ( { iosApiKey, androidApiKey, apiHost, useNativeUI, timeout } )
27- ) ;
28-
25+ const killswitchRef = useRef < Killswitch | null > ( null ) ;
2926 const appState = useAppState ( ) ;
3027 const previousAppState = usePrevious ( appState ) ;
31-
3228 const [ isOk , setIsOk ] = useState < boolean | null > ( null ) ;
3329
30+ const getKillswitch = useCallback ( ( ) => {
31+ if ( killswitchRef . current !== null ) return killswitchRef . current ;
32+
33+ const killswitch = new Killswitch ( {
34+ iosApiKey,
35+ androidApiKey,
36+ apiHost,
37+ useNativeUI,
38+ timeout,
39+ } ) ;
40+
41+ killswitchRef . current = killswitch ;
42+
43+ return killswitch ;
44+ } , [ androidApiKey , apiHost , iosApiKey , timeout , useNativeUI ] ) ;
45+
3446 useEffect ( ( ) => {
3547 async function run ( ) {
3648 if ( previousAppState !== 'active' && appState === 'active' ) {
37- const { isOk : newIsOk } = await killswitch . current . check (
49+ const { isOk : newIsOk } = await getKillswitch ( ) . check (
3850 language ,
3951 version
4052 ) ;
@@ -44,7 +56,7 @@ export function useKillswitch({
4456 }
4557
4658 run ( ) ;
47- } , [ appState , language , previousAppState , version ] ) ;
59+ } , [ appState , getKillswitch , language , previousAppState , version ] ) ;
4860
49- return { isOk, killswitch : killswitch . current } ;
61+ return { isOk, killswitch : getKillswitch ( ) } ;
5062}
0 commit comments