-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoteConfigProvider.tsx
More file actions
73 lines (65 loc) · 1.88 KB
/
RemoteConfigProvider.tsx
File metadata and controls
73 lines (65 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'use client';
import React, {
createContext,
useState,
useEffect,
type ReactNode,
useContext,
} from 'react';
import {
defaultRemoteConfigValues,
matchesFeatureFlagBypass,
type RemoteConfigValues,
} from '../interface/RemoteConfig';
import { useAuthSession } from '../components/AuthSessionProvider';
const RemoteConfigContext = createContext<{
config: RemoteConfigValues;
}>({
config: defaultRemoteConfigValues,
});
interface RemoteConfigProviderProps {
children: ReactNode;
config: RemoteConfigValues;
}
function applyAdminBypass(config: RemoteConfigValues): RemoteConfigValues {
const overridden = { ...config };
for (const key of Object.keys(overridden) as Array<
keyof RemoteConfigValues
>) {
if (typeof overridden[key] === 'boolean') {
(overridden as Record<string, unknown>)[key] = true;
}
}
return overridden;
}
/**
* Client-side Remote Config provider that hydrates server-fetched config into React Context.
* Applies admin bypass for @mobilitydata.org users after client-side auth resolves,
* which ensures correct flags even on statically generated pages.
*/
export const RemoteConfigProvider = ({
children,
config,
}: RemoteConfigProviderProps): React.ReactElement => {
const { email, isAuthReady } = useAuthSession();
const [effectiveConfig, setEffectiveConfig] = useState(config);
useEffect(() => {
if (!isAuthReady) return;
setEffectiveConfig(
matchesFeatureFlagBypass(email, config.featureFlagBypass)
? applyAdminBypass(config)
: config,
);
}, [email, isAuthReady, config]);
return (
<RemoteConfigContext.Provider value={{ config: effectiveConfig }}>
{children}
</RemoteConfigContext.Provider>
);
};
/**
* Hook to access Remote Config values from any client component.
*/
export const useRemoteConfig = (): {
config: RemoteConfigValues;
} => useContext(RemoteConfigContext);