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 Jul 25, 2024
1 parent 46bd639 commit a10baad
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 @@ -219,7 +219,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 @@ -258,4 +258,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 @@ -60,7 +60,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 a10baad

Please sign in to comment.