Created
July 25, 2023 15:14
-
-
Save meshaabi/120c60d1a65e9034488d9b6fc73562b7 to your computer and use it in GitHub Desktop.
This file contains 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 isEqual from 'react-fast-compare'; | |
import { useStore } from 'store/useStore'; | |
import { getCurrentStoreLocale } from 'store/stores/helpers'; | |
import { StoreCode, StoreLocale } from 'store/stores/types'; | |
// import { logError } from 'utils/genericError'; | |
import { RemoteConfigByLocale, RemoteConfigByStore, RemoteConfigState } from './types'; | |
const safeConfig = <T, U extends string>(config: T, scope: U, name: string) => { | |
const { isRemoteConfigReady, remoteConfig } = useStore.getState(); | |
if (config || !isRemoteConfigReady) return config; | |
else { | |
// logError( | |
console.log( | |
`Remote config ${name} for ${scope} is not defined`, | |
new Error('Remote config is not defined'), | |
{ name, scope }, | |
{ name, scope, config, isRemoteConfigReady, remoteConfig }, | |
); | |
} | |
}; | |
export const useRemoteConfig = <T extends keyof RemoteConfigState>(configName: T) => { | |
const config = useStore(state => state.remoteConfig[configName], isEqual); | |
return safeConfig(config, 'root', configName); | |
}; | |
export const useRemoteConfigByStore = <T extends keyof RemoteConfigByStore>(configName: T) => { | |
const currentStore = useStore(state => state.currentStore); | |
const remoteConfig = useStore(state => state.remoteConfig[configName], isEqual); | |
if (currentStore) { | |
const config = remoteConfig?.[currentStore] as RemoteConfigByStore[T][StoreCode]; | |
return safeConfig(config, currentStore, configName); | |
} | |
}; | |
export const useRemoteConfigByLocale = <T extends keyof RemoteConfigByLocale>(configName: T) => { | |
const currentStore = useStore(state => state.currentStore); | |
const currentLocale = getCurrentStoreLocale(currentStore); | |
const remoteConfig = useStore(state => state.remoteConfig[configName], isEqual); | |
if (currentLocale) { | |
const config = remoteConfig?.[currentLocale] as RemoteConfigByLocale[T][StoreLocale]; | |
return safeConfig(config, currentLocale, configName); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment