-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathFlagProvider.tsx
More file actions
78 lines (66 loc) · 2.1 KB
/
FlagProvider.tsx
File metadata and controls
78 lines (66 loc) · 2.1 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
74
75
76
77
78
import type { ReactNode } from "react";
import { useEffect, useState } from "react";
import { FlagProvider as FlagProviderOriginal, useUnleashClient } from "@unleash/nextjs";
import { Loading } from "@src/components/layout/Layout";
import { useUser } from "@src/hooks/useUser";
import type { FCWithChildren } from "@src/types/component";
import { useServices } from "../ServicesProvider";
const COMPONENTS = {
FlagProvider: FlagProviderOriginal,
useUser,
WaitForFeatureFlags
};
export type Props = { components?: typeof COMPONENTS };
export const UserAwareFlagProvider: FCWithChildren<Props> = ({ children, components: c = COMPONENTS }) => {
const { publicConfig } = useServices();
const { user } = c.useUser();
const isEnableAll = publicConfig.NEXT_PUBLIC_UNLEASH_ENABLE_ALL;
return (
<c.FlagProvider
config={{
context: {
userId: user?.id,
sessionId: getSessionId()
},
fetch: isEnableAll ? () => new Response(JSON.stringify({ toggles: [] })) : undefined
}}
>
<c.WaitForFeatureFlags>{children}</c.WaitForFeatureFlags>
</c.FlagProvider>
);
};
export const FlagProvider = UserAwareFlagProvider;
function WaitForFeatureFlags({ children }: { children: ReactNode }) {
const client = useUnleashClient();
const [isReady, setIsReady] = useState(false);
useEffect(() => {
if (client.isReady()) {
setIsReady(true);
return;
}
let callback: (() => void) | undefined;
if (!client.isReady()) {
callback = () => {
if (timerId) clearTimeout(timerId);
setIsReady(true);
};
const timerId = setTimeout(callback, 10_000);
client.once("ready", callback);
client.once("error", callback);
}
return () => {
if (callback) {
client.off("ready", callback);
client.off("error", callback);
}
};
}, [client]);
if (!isReady) {
return <Loading text="Loading application..." />;
}
return <>{children}</>;
}
function getSessionId(): string | undefined {
const m = document.cookie.match(/(?:^|; )unleash-session-id=([^;]+)/);
return m?.[1];
}