Skip to content

Commit

Permalink
Fix Unleash#80: Stop client on unmount
Browse files Browse the repository at this point in the history
  • Loading branch information
melloware committed Sep 26, 2022
1 parent 33ac887 commit 038f758
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/FlagProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ interface renderConsumerOptions {
const getVariantMock = jest.fn().mockReturnValue('A');
const updateContextMock = jest.fn();
const startClientMock = jest.fn();
const stopClientMock = jest.fn();
const onMock = jest.fn().mockReturnValue('subscribed');
const isEnabledMock = jest.fn().mockReturnValue(true);
const UnleashClientSpy: jest.SpyInstance = jest.spyOn(
Expand All @@ -45,6 +46,7 @@ UnleashClientSpy.mockReturnValue({
getVariant: getVariantMock,
updateContext: updateContextMock,
start: startClientMock,
stop: stopClientMock,
isEnabled: isEnabledMock,
on: onMock,
});
Expand Down Expand Up @@ -227,6 +229,7 @@ test('should update when ready event is sent', () => {
getVariant: getVariantMock,
updateContext: updateContextMock,
start: startClientMock,
stop: stopClientMock,
isEnabled: isEnabledMock,
on: localMock,
});
Expand Down Expand Up @@ -258,6 +261,7 @@ test('should register error when error event is sent', () => {
getVariant: getVariantMock,
updateContext: updateContextMock,
start: startClientMock,
stop: stopClientMock,
isEnabled: isEnabledMock,
on: localMock,
});
Expand Down Expand Up @@ -285,10 +289,12 @@ test('should register error when error event is sent', () => {

test('should not start client if startClient is false', () => {
const localMock = jest.fn();
const stopMock = jest.fn();
UnleashClientSpy.mockReturnValue({
getVariant: getVariantMock,
updateContext: updateContextMock,
start: localMock,
stop: stopMock,
isEnabled: isEnabledMock,
on: onMock,
});
Expand All @@ -306,4 +312,5 @@ test('should not start client if startClient is false', () => {
);

expect(localMock).not.toHaveBeenCalled();
expect(stopMock).not.toHaveBeenCalled();
});
11 changes: 11 additions & 0 deletions src/FlagProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,19 @@ const FlagProvider: React.FC<React.PropsWithChildren<IFlagProvider>> = ({
React.useEffect(() => {
const shouldStartClient = startClient || !unleashClient;
if (shouldStartClient) {
// defensively stop the client first
client.current.stop();
// start the client
client.current.start();
}

// stop unleash client on unmount
return function cleanup() {
if (client.current) {
client.current.stop();
client.current = undefined;
}
};
}, []);

const updateContext: IFlagContextValue['updateContext'] = async (context) => {
Expand Down

0 comments on commit 038f758

Please sign in to comment.