Skip to content

Commit defcccb

Browse files
committed
feat(suite-native): init store only if the app is active (foreground)
1 parent 5947fc8 commit defcccb

File tree

1 file changed

+27
-12
lines changed

1 file changed

+27
-12
lines changed

Diff for: suite-native/state/src/StoreProvider.tsx

+27-12
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { ReactNode, useEffect, useState } from 'react';
1+
import { ReactNode, useEffect, useRef, useState } from 'react';
2+
import { AppState } from 'react-native';
23
import { Provider } from 'react-redux';
34

45
import { EnhancedStore } from '@reduxjs/toolkit';
@@ -14,23 +15,37 @@ type StoreProviderProps = {
1415
};
1516

1617
export const StoreProvider = ({ children }: StoreProviderProps) => {
18+
const initStoreCalledRef = useRef(false);
1719
const [store, setStore] = useState<EnhancedStore | null>(null);
1820
const [storePersistor, setStorePersistor] = useState<Persistor | null>(null);
1921

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+
};
2034
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();
3038
}
31-
};
39+
});
40+
41+
if (!initStoreCalledRef.current && AppState.currentState === 'active') {
42+
initStoreAsync();
43+
subscription.remove();
44+
}
3245

33-
initStoreAsync();
46+
return () => {
47+
subscription.remove();
48+
};
3449
}, []);
3550

3651
if (store === null || storePersistor === null) return null;

0 commit comments

Comments
 (0)