Skip to content

Commit

Permalink
fix: edge case on calling cleanup function (#18)
Browse files Browse the repository at this point in the history
fix: edge case on calling cleanup function
  • Loading branch information
himself65 authored Nov 9, 2023
1 parent 5a0f8f9 commit 3cb2b16
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 0 deletions.
10 changes: 10 additions & 0 deletions __tests__/atomEffect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ it('should run the effect on vanilla store', async () => {
await waitFor(() => expect(store.get(countAtom)).toBe(0))
})

it('should not call effect immediately un-subscription', async () => {
expect.assertions(1)
const store = getDefaultStore()
const effect = jest.fn()
const effectAtom = atomEffect(effect)
const unsub = store.sub(effectAtom, () => void 0)
unsub()
expect(effect).not.toHaveBeenCalled()
})

it('should run the effect on mount and cleanup on unmount once', async () => {
expect.assertions(5)
const effect = { mount: 0, unmount: 0 }
Expand Down
1 change: 1 addition & 0 deletions src/atomEffect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export function atomEffect(
++ref.inProgress
return (ref.promise = Promise.resolve().then(() => {
try {
if (!ref.mounted) return
ref.cleanup?.()
ref.cleanup = effectFn(get, setSelf as Setter)
} finally {
Expand Down

0 comments on commit 3cb2b16

Please sign in to comment.