Skip to content

Commit

Permalink
Merge pull request HubSpot#94 from gmcnaughton/gcm/fix-different-prop…
Browse files Browse the repository at this point in the history
…s-in-same-render-cycle

Fixes bad intermediate return values from `useStoreDependency`
  • Loading branch information
aem authored Feb 18, 2021
2 parents e7963fe + eba669f commit 5569034
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/dependencies/__tests__/useStoreDependency-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,28 @@ describe('useStoreDependency', () => {
testHook(useCallback);
});

it('returns the updated store value after prop update', () => {
const Component = ({ factor }) => {
const value = useStoreDependency(multiplyDependency, { factor });
if (value !== factor) {
// We need to throw here rather than relying on the `expect` below
// to catch invalid return values.
//
// This component ends up re-rendering twice: once for the explicit `setProps`
// call, and once for the internal `setState` call inside `useStoreDependency`.
// The expected end state is eventually reached, but intermediate return
// values from `useStoreDependency` could still be wrong.
throw new Error(`incorrect return value from useStoreDependency: expected ${factor} but received ${value}`);
}
return <div data-value={value} />;
};
const rendered = mount(<Component factor={4} />);
expect(rendered.find('div').prop('data-value')).toBe(4);
rendered.setProps({ factor: 8 });
rendered.update();
expect(rendered.find('div').prop('data-value')).toBe(8);
});

it('handles a prop update', () => {
const Component = ({ factor = 4 }) => {
const value = useStoreDependency(multiplyDependency, { factor });
Expand Down
1 change: 1 addition & 0 deletions src/dependencies/useStoreDependency.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,7 @@ function useStoreDependency<Props, DepType>(
const newValue = { dependency: calculate(dependency, props) };
if (!shallowEqual(newValue.dependency, dependencyValue.dependency)) {
setDependencyValue(newValue);
return newValue.dependency;
}
return dependencyValue.dependency;
}
Expand Down

0 comments on commit 5569034

Please sign in to comment.