Skip to content

Commit

Permalink
fix(react): restore useAtomSelector mounted state when swapping inl…
Browse files Browse the repository at this point in the history
…ine refs (#108)
  • Loading branch information
bowheart authored Jul 30, 2024
1 parent 71dcf06 commit 4f7fba6
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/react/src/hooks/useAtomSelector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export const useAtomSelector = <T, Args extends any[]>(
selectorOrConfig as AtomSelectorOrConfig<any, any[]>,
resolvedArgs
)
;(render as any).mounted = false
;(render as any).mounted = true
}

const cache = isSwappingRefs
Expand Down
48 changes: 48 additions & 0 deletions packages/react/test/units/useAtomSelector.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -567,4 +567,52 @@ describe('useAtomSelector', () => {
expect(renders).toBe(6) // 3 rerenders + 3 for strict mode
expect(ecosystem._graph.nodes).toMatchSnapshot()
})

test('inline selector stays subscribed after being swapped out', async () => {
jest.useFakeTimers()
const atom1 = atom('1', () => ({ val: 1 }))
const selector = ({ get }: AtomGetters) => get(atom1)

function Test() {
const { val } = useAtomSelector({
resultsComparator: (a, b) => a.val === b.val,
selector,
})

return (
<>
<div data-testid="text">{val}</div>
</>
)
}

const { findByTestId } = renderInEcosystem(<Test />, {
useStrictMode: true,
})

const div = await findByTestId('text')

expect(div.innerHTML).toBe('1')

act(() => {
ecosystem.getInstance(atom1).setState({ val: 2 })
jest.runAllTimers()
})

expect(div.innerHTML).toBe('2')

act(() => {
ecosystem.getInstance(atom1).setState({ val: 3 })
jest.runAllTimers()
})

expect(div.innerHTML).toBe('3')

act(() => {
ecosystem.getInstance(atom1).setState({ val: 4 })
jest.runAllTimers()
})

expect(div.innerHTML).toBe('4')
})
})

0 comments on commit 4f7fba6

Please sign in to comment.