-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathFlagProvider.tsx
70 lines (56 loc) · 1.65 KB
/
FlagProvider.tsx
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
import * as React from 'react';
import FlagContext from './FlagContext';
import { UnleashClient, IConfig, IContext } from 'unleash-proxy-client';
interface IFlagProvider {
config: IConfig;
}
const FlagProvider: React.FC<IFlagProvider> = ({ config, children }) => {
const [client, setClient] = React.useState(null);
const functionCalls = React.useRef<any>();
functionCalls.current = [];
React.useEffect(() => {
const client = new UnleashClient(config);
functionCalls.current.forEach((call: any) => {
call(client);
}, []);
functionCalls.current = [];
setClient(client);
client.start();
}, []);
const updateContext = (context: IContext) => {
if (!client) {
deferCall((client: any) => client.updateContext(context));
return;
}
client.updateContext(context);
};
const deferCall = (callback: (client: any) => void) => {
functionCalls.current.push(callback);
};
const isEnabled = (name: string) => {
if (!client) {
deferCall((client: any) => client.isEnabled(name));
return;
}
return client.isEnabled(name);
};
const getVariant = (name: string) => {
if (!client) {
deferCall((client: any) => client.getVariant(name));
return {};
}
return client.getVariant(name);
};
const on = (event:string, ...args:any[]) => {
if (!client) {
deferCall((client: any) => client.on(event,...args));
return;
}
return client.on(event, ...args);
};
const context = { on, updateContext, isEnabled, getVariant, client };
return (
<FlagContext.Provider value={context}>{children}</FlagContext.Provider>
);
};
export default FlagProvider;