Created
July 25, 2023 15:15
-
-
Save meshaabi/e150a657f69b63a5e480f7e9a00bcb3a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import NetInfo from '@react-native-community/netinfo'; | |
import remoteConfig from '@react-native-firebase/remote-config'; | |
import { AppState } from 'react-native'; | |
import { RemoteConfigState } from 'store/remoteConfig/types'; | |
import { useStore } from 'store/useStore'; | |
import { logError } from 'utils/genericError'; | |
const DEFAULT_CONFIG_DURATION = __DEV__ ? 0 : 30 * 60; // 30 mins | |
const fbConfig = remoteConfig(); | |
const syncRemoteConfig = () => { | |
fbConfig.fetchAndActivate().then(async fetchedRemotely => { | |
if (fetchedRemotely) { | |
const { setRemoteConfig } = useStore.getState(); | |
await fbConfig.ensureInitialized(); | |
const parameters = remoteConfig().getAll(); | |
const config: RemoteConfigState = {}; | |
Object.entries(parameters).forEach($ => { | |
const [key, entry] = $; | |
try { | |
config[key as keyof RemoteConfigState] = JSON.parse(entry.asString()); | |
} catch (error) { | |
logError( | |
'updateRemoteConfig', | |
error, | |
{ key, source: entry.getSource() }, | |
{ entry: entry.asString() }, | |
); | |
} | |
}); | |
setRemoteConfig(config); | |
} | |
}); | |
}; | |
export const initRemoteConfig = () => { | |
fbConfig.setConfigSettings({ | |
minimumFetchIntervalMillis: DEFAULT_CONFIG_DURATION, | |
}); | |
AppState.addEventListener('change', async nextAppState => { | |
if (nextAppState === 'active') { | |
syncRemoteConfig(); | |
} | |
}); | |
NetInfo.addEventListener(({ isConnected, isInternetReachable }) => { | |
if (isConnected && isInternetReachable) { | |
syncRemoteConfig(); | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment