-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathFlagProvider.tsx
68 lines (54 loc) · 1.53 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
/** @format */
import * as React from 'react';
import FlagContext from './FlagContext';
import { UnleashClient, IConfig, IContext } from 'unleash-proxy-client';
type eventArgs = [Function, any];
interface IFlagProvider {
config?: IConfig;
unleashClient?: UnleashClient;
}
const FlagProvider: React.FC<IFlagProvider> = ({
config,
children,
unleashClient,
}) => {
const client = React.useRef<UnleashClient>(unleashClient);
if (!config && !unleashClient) {
console.warn(
`You must provide either a config or an unleash client to the flag provider. If you are initializing the client in useEffect, you can avoid this warning by
checking if the client exists before rendering.`
);
}
if (!client.current) {
client.current = new UnleashClient(config);
}
React.useEffect(() => {
client.current.start();
}, []);
const updateContext = async (context: IContext): Promise<void> => {
await client.current.updateContext(context);
};
const isEnabled = (name: string) => {
return client.current.isEnabled(name);
};
const getVariant = (name: string) => {
return client.current.getVariant(name);
};
const on = (event: string, ...args: eventArgs) => {
return client.current.on(event, ...args);
};
const context = React.useMemo(
() => ({
on,
updateContext,
isEnabled,
getVariant,
client: client.current,
}),
[]
);
return (
<FlagContext.Provider value={context}>{children}</FlagContext.Provider>
);
};
export default FlagProvider;