Skip to content

Commit

Permalink
call subscribers when setatom changes value in onmount
Browse files Browse the repository at this point in the history
  • Loading branch information
dmaskasky committed Nov 14, 2024
1 parent d9091a1 commit 371a9bf
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/vanilla/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -664,9 +664,9 @@ const buildStore = (
const pending = createPending()
const atomState = getAtomState(atom)
const mounted = mountAtom(pending, atom, atomState)
flushPending(pending)
const listeners = mounted.l
listeners.add(listener)
flushPending(pending)
return () => {
listeners.delete(listener)
const pending = createPending()
Expand Down
23 changes: 23 additions & 0 deletions tests/vanilla/store.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -876,3 +876,26 @@ describe('should mount and trigger listeners even when an error is thrown', () =
expect(listener).toHaveBeenCalledOnce()
})
})

it('should call subscribers after setAtom updates atom value on mount but not on unmount', () => {
const store = createStore()
const a = atom(0)
let unmount
a.onMount = vi.fn(((setAtom) => {
setAtom(1)
unmount = vi.fn(() => {
setAtom(2)
})
return unmount
}) as NonNullable<(typeof a)['onMount']>)
const listener = vi.fn()
const unsub = store.sub(a, listener)
expect(store.get(a)).toBe(1)
expect(a.onMount).toHaveBeenCalledTimes(1)
expect(listener).toHaveBeenCalledTimes(1)
listener.mockClear()
unsub()
expect(store.get(a)).toBe(2)
expect(unmount).toHaveBeenCalledTimes(1)
expect(listener).toHaveBeenCalledTimes(0)
})

0 comments on commit 371a9bf

Please sign in to comment.