Skip to content

Commit

Permalink
fix(hooks): update useFeature decisions when forced variation updates
Browse files Browse the repository at this point in the history
  • Loading branch information
jscarmona committed Sep 10, 2021
1 parent 62f8942 commit 0089347
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Feature.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ describe('<OptimizelyFeature>', () => {
attributes: {},
},
isReady: jest.fn().mockReturnValue(false),
onForcedVariationsUpdate: jest.fn().mockReturnValue(() => {}),
} as unknown) as ReactSDKClient;
});
it('throws an error when not rendered in the context of an OptimizelyProvider', () => {
Expand Down
18 changes: 18 additions & 0 deletions src/hooks.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -666,6 +666,24 @@ describe('hooks', () => {
component.update();
expect(isFeatureEnabledMock).not.toHaveBeenCalled();
});

it('should re-render after setForcedVariation is called on the client', async () => {
isFeatureEnabledMock.mockReturnValue(false);
const component = Enzyme.mount(
<OptimizelyProvider optimizely={optimizelyMock}>
<MyFeatureComponent options={{ autoUpdate: true }} />
</OptimizelyProvider>
);

component.update();
expect(component.text()).toBe('false|{"foo":"bar"}|true|false');

isFeatureEnabledMock.mockReturnValue(true);
forcedVariationUpdateCallbacks[0]();

component.update();
expect(component.text()).toBe('true|{"foo":"bar"}|true|false');
});
});

describe('useDecision', () => {
Expand Down
11 changes: 11 additions & 0 deletions src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -319,6 +319,17 @@ export const useFeature: UseFeature = (featureKey, options = {}, overrides = {})
return (): void => {};
}, [isClientReady, options.autoUpdate, optimizely, featureKey, getCurrentDecision]);

useEffect(
() =>
optimizely.onForcedVariationsUpdate(() => {
setState(prevState => ({
...prevState,
...getCurrentDecision(),
}));
}),
[getCurrentDecision, optimizely]
);

return [state.isEnabled, state.variables, state.clientReady, state.didTimeout];
};

Expand Down

0 comments on commit 0089347

Please sign in to comment.