-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathuseVariant.ts
48 lines (39 loc) · 1.26 KB
/
useVariant.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
import { useContext, useState, useEffect, useRef } from 'react';
import { IVariant } from 'unleash-proxy-client';
import FlagContext from './FlagContext';
const useVariant = (name: string): Partial<IVariant> => {
const { getVariant, client } = useContext(FlagContext);
const [variant, setVariant] = useState(getVariant(name));
const variantRef = useRef<typeof variant>({
name: variant.name,
enabled: variant.enabled,
});
variantRef.current = variant;
useEffect(() => {
if (!client) return;
const updateHandler = () => {
const newVariant = getVariant(name);
if (
variantRef.current.name !== newVariant?.name ||
variantRef.current.enabled !== newVariant?.enabled
) {
setVariant(newVariant);
variantRef.current = newVariant;
}
};
const readyHandler = () => {
const variant = getVariant(name);
variantRef.current.name = variant?.name;
variantRef.current.enabled = variant?.enabled;
setVariant(variant);
};
client.on('update', updateHandler);
client.on('ready', readyHandler);
return () => {
client.off('update', updateHandler);
client.off('ready', readyHandler);
};
}, [client]);
return variant || {};
};
export default useVariant;