From defcccb3b0334776b343168ccaf74c92f43d999b Mon Sep 17 00:00:00 2001 From: Matej Kriz Date: Wed, 5 Feb 2025 10:42:43 +0100 Subject: [PATCH] feat(suite-native): init store only if the app is active (foreground) --- suite-native/state/src/StoreProvider.tsx | 39 ++++++++++++++++-------- 1 file changed, 27 insertions(+), 12 deletions(-) diff --git a/suite-native/state/src/StoreProvider.tsx b/suite-native/state/src/StoreProvider.tsx index 29f270a0d11..fa8d1f88931 100644 --- a/suite-native/state/src/StoreProvider.tsx +++ b/suite-native/state/src/StoreProvider.tsx @@ -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'; @@ -14,23 +15,37 @@ type StoreProviderProps = { }; export const StoreProvider = ({ children }: StoreProviderProps) => { + const initStoreCalledRef = useRef(false); const [store, setStore] = useState(null); const [storePersistor, setStorePersistor] = useState(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;