1
- import { ReactNode , useEffect , useState } from 'react' ;
1
+ import { ReactNode , useEffect , useRef , useState } from 'react' ;
2
+ import { AppState } from 'react-native' ;
2
3
import { Provider } from 'react-redux' ;
3
4
4
5
import { EnhancedStore } from '@reduxjs/toolkit' ;
@@ -14,23 +15,37 @@ type StoreProviderProps = {
14
15
} ;
15
16
16
17
export const StoreProvider = ( { children } : StoreProviderProps ) => {
18
+ const initStoreCalledRef = useRef ( false ) ;
17
19
const [ store , setStore ] = useState < EnhancedStore | null > ( null ) ;
18
20
const [ storePersistor , setStorePersistor ] = useState < Persistor | null > ( null ) ;
19
21
22
+ const initStoreAsync = async ( ) => {
23
+ initStoreCalledRef . current = true ;
24
+ try {
25
+ const freshStore = await initStore ( ) ;
26
+ const freshPersistor = persistStore ( freshStore ) ;
27
+ setStore ( freshStore ) ;
28
+ setStorePersistor ( freshPersistor ) ;
29
+ } catch ( error ) {
30
+ console . error ( 'Init store error:' , error ) ;
31
+ Sentry . captureException ( error ) ;
32
+ }
33
+ } ;
20
34
useEffect ( ( ) => {
21
- const initStoreAsync = async ( ) => {
22
- try {
23
- const freshStore = await initStore ( ) ;
24
- const freshPersistor = persistStore ( freshStore ) ;
25
- setStore ( freshStore ) ;
26
- setStorePersistor ( freshPersistor ) ;
27
- } catch ( error ) {
28
- console . error ( 'Init store error:' , error ) ;
29
- Sentry . captureException ( error ) ;
35
+ const subscription = AppState . addEventListener ( 'change' , nextAppState => {
36
+ if ( ! initStoreCalledRef . current && nextAppState === 'active' ) {
37
+ initStoreAsync ( ) ;
30
38
}
31
- } ;
39
+ } ) ;
40
+
41
+ if ( ! initStoreCalledRef . current && AppState . currentState === 'active' ) {
42
+ initStoreAsync ( ) ;
43
+ subscription . remove ( ) ;
44
+ }
32
45
33
- initStoreAsync ( ) ;
46
+ return ( ) => {
47
+ subscription . remove ( ) ;
48
+ } ;
34
49
} , [ ] ) ;
35
50
36
51
if ( store === null || storePersistor === null ) return null ;
0 commit comments