Skip to content

Commit 7980125

Browse files
committed
feat: fix context value reference change across render
1 parent e1e5c28 commit 7980125

File tree

1 file changed

+35
-8
lines changed

1 file changed

+35
-8
lines changed

src/FlagProvider.tsx

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/** @format */
22

3-
import React, { type FC, type PropsWithChildren, useEffect, useMemo, useState } from 'react';
4-
import { type IConfig, UnleashClient } from 'unleash-proxy-client';
3+
import React, { type FC, type PropsWithChildren, useCallback, useEffect, useMemo, useState } from 'react';
4+
import { type IConfig, IMutableContext, UnleashClient } from 'unleash-proxy-client';
55
import FlagContext, { type IFlagContextValue } from './FlagContext';
66

77
export interface IFlagProvider {
@@ -106,20 +106,47 @@ const FlagProvider: FC<PropsWithChildren<IFlagProvider>> = ({
106106
};
107107
}, []);
108108

109+
const on = useCallback(
110+
(event: string, callback: Function, ctx?: any) =>
111+
client.current.on(event, callback, ctx),
112+
[]
113+
) as IFlagContextValue['on'];
114+
115+
const off = useCallback(
116+
(event: string, callback?: Function) => client.current.off(event, callback),
117+
[]
118+
) as IFlagContextValue['off'];
119+
120+
const isEnabled = useCallback(
121+
(toggleName: string) => client.current.isEnabled(toggleName),
122+
[]
123+
) as IFlagContextValue['isEnabled'];
124+
125+
const updateContext = useCallback(
126+
async (context: IMutableContext) =>
127+
await client.current.updateContext(context),
128+
[]
129+
) as IFlagContextValue['updateContext'];
130+
131+
const getVariant = useCallback(
132+
(toggleName: string) => client.current.getVariant(toggleName),
133+
[]
134+
) as IFlagContextValue['getVariant'];
135+
109136
const context = useMemo<IFlagContextValue>(
110137
() => ({
111-
on: ((event, callback, ctx) => client.current.on(event, callback, ctx)) as IFlagContextValue['on'],
112-
off: ((event, callback) => client.current.off(event, callback)) as IFlagContextValue['off'],
113-
updateContext: async (context) => await client.current.updateContext(context),
114-
isEnabled: (toggleName) => client.current.isEnabled(toggleName),
115-
getVariant: (toggleName) => client.current.getVariant(toggleName),
138+
on,
139+
off,
140+
updateContext,
141+
isEnabled,
142+
getVariant,
116143
client: client.current,
117144
flagsReady,
118145
flagsError,
119146
setFlagsReady,
120147
setFlagsError,
121148
}),
122-
[flagsReady, flagsError]
149+
[flagsReady, flagsError, on, off, updateContext, isEnabled, getVariant]
123150
);
124151

125152
return (

0 commit comments

Comments
 (0)