Skip to content

Commit b157a48

Browse files
committed
Fix edge case of facet effects without facets
1 parent c7a10cf commit b157a48

2 files changed

Lines changed: 24 additions & 0 deletions

File tree

packages/@react-facet/core/src/hooks/useFacetEffect.spec.tsx

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,26 @@ import { useFacetEffect } from './useFacetEffect'
44
import { createFacet } from '../facet'
55
import { NO_VALUE } from '../types'
66

7+
it('triggers the effect on mount, even if no facet is provided', () => {
8+
const cleanup = jest.fn()
9+
const callback = jest.fn().mockReturnValue(cleanup)
10+
11+
const ComponentWithFacetEffect = () => {
12+
useFacetEffect(callback, [], [])
13+
14+
return null
15+
}
16+
17+
const result = render(<ComponentWithFacetEffect />)
18+
expect(callback).toHaveBeenCalledTimes(1)
19+
expect(cleanup).not.toHaveBeenCalled()
20+
21+
callback.mockClear()
22+
result.rerender(<></>)
23+
expect(callback).not.toHaveBeenCalled()
24+
expect(cleanup).toHaveBeenCalledTimes(1)
25+
})
26+
727
it('triggers the effect on mount with the initial value and on any update of the facet', () => {
828
const demoFacet = createFacet({ initialValue: 'initial value' })
929

packages/@react-facet/core/src/hooks/useFacetEffect.tsx

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ export const createUseFacetEffect = (useHook: typeof useEffect | typeof useLayou
1414
useHook(() => {
1515
let cleanup: void | Cleanup
1616

17+
if (facets.length === 0) {
18+
return effectMemoized()
19+
}
20+
1721
if (facets.length === 1) {
1822
const unsubscribe = facets[0].observe((value) => {
1923
if (cleanup !== undefined) {

0 commit comments

Comments
 (0)