import { createContext , FC , useContext , useEffect } from 'react' ; import { useDispatch , useSelector } from '@store' ; import { FeatureFlag , getFeatureFlags , resetFeatureFlags as resetFeatureFlagsAction , setFeatureFlag as setFeatureFlagAction } from './slice' ; export interface IFeatureFlagContext { featureFlags : ReturnType < typeof getFeatureFlags > ; isFeatureActive ( f ) : boolean ; setFeatureFlag ( key , value ) : void ; resetFeatureFlags ( ) : void ; } export const FeatureFlagContext = createContext ( { } as IFeatureFlagContext ) ; export const FeatureFlagProvider = ( { children } ) => { const dispatch = useDispatch ( ) ; const featureFlags = useSelector ( getFeatureFlags ) ; const setFeatureFlag = ( key , value ) => dispatch ( setFeatureFlagAction ( { feature : key , isActive : value } ) ) ; const resetFeatureFlags = ( ) => dispatch ( resetFeatureFlagsAction ( ) ) ; const isFeatureActive = ( f ) => ! ! featureFlags [ f ] ; useEffect ( ( ) => { ( window as CustomWindow ) . setFeatureFlag = setFeatureFlag ; ( window as CustomWindow ) . resetFeatureFlags = resetFeatureFlags ; } ) ; const stateContext = { featureFlags , isFeatureActive , setFeatureFlag , resetFeatureFlags } ; return < FeatureFlagContext . Provider value = { stateContext } > { children } < /FeatureFlagContext.Provider>; } ; export function useFeatureFlags ( ) { const context = useContext ( FeatureFlagContext ) ; if ( context === undefined ) { throw new Error ( 'useFeatureFlags must be used with a Feature Flag Provider' ) ; } return context ; }