Skip to content

Commit

Permalink
Fix useFacetUnwrap support for custom equality check (#140)
Browse files Browse the repository at this point in the history
* Fix test catching the bug

* Properly checks if the new value is the same as the previous one

The prior implementation would always compare the previous with itself

* Refactor so that in never calls setState, unless needed

* Revert "Refactor so that in never calls setState, unless needed"

This reverts commit dd53972.
  • Loading branch information
pirelenito authored and marlonicus committed Aug 12, 2024
1 parent 065e744 commit 1213b40
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
16 changes: 15 additions & 1 deletion packages/@react-facet/core/src/hooks/useFacetUnwrap.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ it('does not trigger a re-render when changing a facet from undefined to undefin
})

it('supports custom equality checks', () => {
const value = {}
const value = { prop: 'initial' }
const demoFacet = createFacet({ initialValue: value })

// Dummy equality check that always returns its not equal
Expand Down Expand Up @@ -267,4 +267,18 @@ it('supports custom equality checks', () => {
expect(check).toHaveBeenCalledTimes(1) // but the check should be executed
expect(check).toHaveBeenCalledWith(value) // passing the value (which should be the same)
expect(renderedMock).toHaveBeenCalledTimes(1) // and since the equality check always returns "false", we have a render

jest.clearAllMocks()

const newValue = { prop: 'new' }

// If we update with a new object,
act(() => {
demoFacet.set(newValue)
})

expect(equalityCheck).toHaveBeenCalledTimes(0) // equality check was already initialized
expect(check).toHaveBeenCalledTimes(1) // but the check should be executed
expect(check).toHaveBeenCalledWith(newValue) // passing the new value
expect(renderedMock).toHaveBeenCalledTimes(1) // and since the equality check always returns "false", we have a render
})
2 changes: 1 addition & 1 deletion packages/@react-facet/core/src/hooks/useFacetUnwrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ export function useFacetUnwrap<T extends Value>(
return { value }
}

if (previousValue !== NO_VALUE && isEqual(previousValue)) {
if (previousValue !== NO_VALUE && isEqual(value)) {
return previousState
}

Expand Down

0 comments on commit 1213b40

Please sign in to comment.