Changeset View
Changeset View
Standalone View
Standalone View
native/components/feature-flags-provider.react.js
// @flow | // @flow | ||||
import * as React from 'react'; | import * as React from 'react'; | ||||
import { Platform } from 'react-native'; | |||||
import { fetchFeatureFlags } from 'lib/utils/feature-flags-utils.js'; | |||||
import { useIsCurrentUserStaff } from 'native/utils/staff-utils.js'; | |||||
import { codeVersion } from '../redux/persist.js'; | |||||
type FeatureFlagsConfiguration = { | type FeatureFlagsConfiguration = { | ||||
+[feature: string]: boolean, | +[feature: string]: boolean, | ||||
}; | }; | ||||
type FeatureFlagsContextType = { | type FeatureFlagsContextType = { | ||||
+configuration: FeatureFlagsConfiguration, | +configuration: FeatureFlagsConfiguration, | ||||
+loaded: boolean, | +loaded: boolean, | ||||
}; | }; | ||||
const defaultContext = { | const defaultContext = { | ||||
configuration: {}, | configuration: {}, | ||||
loaded: false, | loaded: false, | ||||
}; | }; | ||||
const FeatureFlagsContext: React.Context<FeatureFlagsContextType> = | const FeatureFlagsContext: React.Context<FeatureFlagsContextType> = | ||||
React.createContext<FeatureFlagsContextType>(defaultContext); | React.createContext<FeatureFlagsContextType>(defaultContext); | ||||
type Props = { | type Props = { | ||||
+children: React.Node, | +children: React.Node, | ||||
}; | }; | ||||
function FeatureFlagsProvider(props: Props): React.Node { | function FeatureFlagsProvider(props: Props): React.Node { | ||||
const { children } = props; | const { children } = props; | ||||
const isStaff = useIsCurrentUserStaff(); | |||||
const [featuresConfig, setFeaturesConfig] = React.useState(defaultContext); | |||||
React.useEffect(() => { | |||||
(async () => { | |||||
try { | |||||
const config = await fetchFeatureFlags( | |||||
Platform.OS, | |||||
isStaff, | |||||
codeVersion, | |||||
); | |||||
const configuration = {}; | |||||
for (const feature of config.enabledFeatures) { | |||||
configuration[feature] = true; | |||||
} | |||||
setFeaturesConfig({ | |||||
configuration, | |||||
loaded: true, | |||||
}); | |||||
} catch (e) { | |||||
console.error('Feature flag retrieval failed:', e); | |||||
} | |||||
})(); | |||||
}, [isStaff]); | |||||
return ( | return ( | ||||
<FeatureFlagsContext.Provider value={defaultContext}> | <FeatureFlagsContext.Provider value={featuresConfig}> | ||||
{children} | {children} | ||||
</FeatureFlagsContext.Provider> | </FeatureFlagsContext.Provider> | ||||
); | ); | ||||
} | } | ||||
export { FeatureFlagsContext, FeatureFlagsProvider }; | export { FeatureFlagsContext, FeatureFlagsProvider }; |