Skip to content

Commit

Permalink
feat(suite-native): init store only if the app is active (foreground)
Browse files Browse the repository at this point in the history
  • Loading branch information
matejkriz committed Feb 5, 2025
1 parent 5947fc8 commit defcccb
Showing 1 changed file with 27 additions and 12 deletions.
39 changes: 27 additions & 12 deletions suite-native/state/src/StoreProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ReactNode, useEffect, useState } from 'react';
import { ReactNode, useEffect, useRef, useState } from 'react';
import { AppState } from 'react-native';
import { Provider } from 'react-redux';

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

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

const initStoreAsync = async () => {
initStoreCalledRef.current = true;
try {
const freshStore = await initStore();
const freshPersistor = persistStore(freshStore);
setStore(freshStore);
setStorePersistor(freshPersistor);
} catch (error) {
console.error('Init store error:', error);
Sentry.captureException(error);
}
};
useEffect(() => {
const initStoreAsync = async () => {
try {
const freshStore = await initStore();
const freshPersistor = persistStore(freshStore);
setStore(freshStore);
setStorePersistor(freshPersistor);
} catch (error) {
console.error('Init store error:', error);
Sentry.captureException(error);
const subscription = AppState.addEventListener('change', nextAppState => {
if (!initStoreCalledRef.current && nextAppState === 'active') {
initStoreAsync();
}
};
});

if (!initStoreCalledRef.current && AppState.currentState === 'active') {
initStoreAsync();
subscription.remove();
}

initStoreAsync();
return () => {
subscription.remove();
};
}, []);

if (store === null || storePersistor === null) return null;
Expand Down

0 comments on commit defcccb

Please sign in to comment.