-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathuseFlagContext.ts
61 lines (57 loc) · 1.63 KB
/
useFlagContext.ts
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
import { useContext } from "react";
import FlagContext, { type IFlagContextValue } from "./FlagContext";
import type { UnleashClient } from "unleash-proxy-client";
const methods = {
on: (event: string, callback: Function, ctx?: any): UnleashClient => {
console.error("on() must be used within a FlagProvider");
return mockUnleashClient;
},
off: (event: string, callback?: Function): UnleashClient => {
console.error("off() must be used within a FlagProvider");
return mockUnleashClient;
},
updateContext: async () => {
console.error("updateContext() must be used within a FlagProvider");
return undefined;
},
isEnabled: () => {
console.error("isEnabled() must be used within a FlagProvider");
return false;
},
getVariant: () => {
console.error("getVariant() must be used within a FlagProvider");
return { name: "disabled", enabled: false };
}
};
const mockUnleashClient = {
...methods,
toggles: [],
impressionDataAll: {},
context: {},
storage: {},
start: () => {},
stop: () => {},
isReady: () => false,
getError: () => null,
getAllToggles: () => []
} as unknown as UnleashClient;
const defaultContextValue: IFlagContextValue = {
...methods,
client: mockUnleashClient,
flagsReady: false,
setFlagsReady: () => {
console.error("setFlagsReady() must be used within a FlagProvider");
},
flagsError: null,
setFlagsError: () => {
console.error("setFlagsError() must be used within a FlagProvider");
}
};
export function useFlagContext() {
const context = useContext(FlagContext);
if (!context) {
console.error("useFlagContext() must be used within a FlagProvider");
return defaultContextValue;
}
return context;
}