diff --git a/src/vanilla/store.ts b/src/vanilla/store.ts index 3684c00e65c..0e077ff99bb 100644 --- a/src/vanilla/store.ts +++ b/src/vanilla/store.ts @@ -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() diff --git a/tests/vanilla/store.test.tsx b/tests/vanilla/store.test.tsx index 8a765240a06..c6f410d834a 100644 --- a/tests/vanilla/store.test.tsx +++ b/tests/vanilla/store.test.tsx @@ -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) +})