Skip to content

Commit

Permalink
call subscribers when setatom changes value in onmount (#2815)
Browse files Browse the repository at this point in the history
Co-authored-by: Daishi Kato <[email protected]>
  • Loading branch information
dmaskasky and dai-shi authored Nov 17, 2024
1 parent 1bf91ce commit c41a6de
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 @@ -666,9 +666,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 @@ -910,3 +910,26 @@ it('should use the correct pending on unmount', () => {
expect(store.get(a)).toBe(1)
expect(aListener).toHaveBeenCalledTimes(1)
})

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 c41a6de

Please sign in to comment.