|
| 1 | +import { ReactNode, useCallback, useRef, useState } from "react"; |
| 2 | +import { |
| 3 | + Experiment, |
| 4 | + ExperimentClient, |
| 5 | + Variants, |
| 6 | +} from "@amplitude/experiment-js-client"; |
| 7 | +import { FEATURE_FLAGS } from "./feature-flags"; |
| 8 | +import { FeatureFlagsContext } from "./featureFlagsContext"; |
| 9 | + |
| 10 | +const publicDeploymentKey = "client-jAXxBGw14klnGdfOPcGCrIpbvpvBXZqL"; |
| 11 | + |
| 12 | +export function FeatureFlagsProvider({ children }: { children: ReactNode }) { |
| 13 | + const [flags, setFlags] = useState<Variants>({}); |
| 14 | + const [isLoading, setIsLoading] = useState(false); |
| 15 | + const [isInitialized, setIsInitialized] = useState(false); |
| 16 | + const experimentClientRef = useRef<ExperimentClient | null>(null); |
| 17 | + |
| 18 | + const initializeFeatureFlags = useCallback(() => { |
| 19 | + if (experimentClientRef.current) { |
| 20 | + console.warn("Experiment client already initialized"); |
| 21 | + return; |
| 22 | + } |
| 23 | + experimentClientRef.current = Experiment.initializeWithAmplitudeAnalytics( |
| 24 | + publicDeploymentKey, |
| 25 | + {} |
| 26 | + ); |
| 27 | + // set flags from localstorage cache before a fetch is initialized |
| 28 | + setFlags(experimentClientRef.current.all()); |
| 29 | + setIsInitialized(true); |
| 30 | + }, []); |
| 31 | + |
| 32 | + const fetchFlags = useCallback(async () => { |
| 33 | + if (!experimentClientRef.current) { |
| 34 | + console.error( |
| 35 | + "Experiment client not initialized. Call initializeExperiment() first." |
| 36 | + ); |
| 37 | + return; |
| 38 | + } |
| 39 | + |
| 40 | + try { |
| 41 | + setIsLoading(true); |
| 42 | + await experimentClientRef.current.fetch(undefined, { |
| 43 | + flagKeys: [...FEATURE_FLAGS], |
| 44 | + }); |
| 45 | + setFlags(experimentClientRef.current.all()); |
| 46 | + } catch (error) { |
| 47 | + console.error("Failed to fetch feature flags:", error); |
| 48 | + } finally { |
| 49 | + setIsLoading(false); |
| 50 | + } |
| 51 | + }, []); |
| 52 | + |
| 53 | + return ( |
| 54 | + <FeatureFlagsContext.Provider |
| 55 | + value={{ |
| 56 | + flags, |
| 57 | + isLoading, |
| 58 | + isInitialized, |
| 59 | + initializeFeatureFlags, |
| 60 | + fetchFlags, |
| 61 | + }} |
| 62 | + > |
| 63 | + {children} |
| 64 | + </FeatureFlagsContext.Provider> |
| 65 | + ); |
| 66 | +} |
0 commit comments