Skip to content

Commit

Permalink
fix: setAtom should use the correct pending on unmount
Browse files Browse the repository at this point in the history
  • Loading branch information
dmaskasky committed Nov 14, 2024
1 parent d9091a1 commit 0f0e1a2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
10 changes: 6 additions & 4 deletions src/vanilla/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ type Mounted = {
/** Set of mounted atoms that depends on the atom. */
readonly t: Set<AnyAtom>
/** Function to run when the atom is unmounted. */
u?: OnUnmount
u?: (pending: Pending) => void
}

/**
Expand Down Expand Up @@ -602,18 +602,20 @@ const buildStore = (
const mounted = atomState.m
addPendingFunction(pending, () => {
let isSync = true
let currPending = pending
try {
const onUnmount = atomOnMount(atom, (...args) => {
try {
return writeAtomState(pending, atom, ...args)
return writeAtomState(currPending, atom, ...args)
} finally {
if (!isSync) {
flushPending(pending)
}
}
})
if (onUnmount) {
mounted.u = () => {
mounted.u = (pending) => {
currPending = pending
isSync = true
try {
onUnmount()
Expand Down Expand Up @@ -644,7 +646,7 @@ const buildStore = (
// unmount self
const onUnmount = atomState.m.u
if (onUnmount) {
addPendingFunction(pending, onUnmount)
addPendingFunction(pending, () => onUnmount(pending))
}
delete atomState.m
if (import.meta.env?.MODE !== 'production') {
Expand Down
14 changes: 14 additions & 0 deletions tests/vanilla/store.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -876,3 +876,17 @@ describe('should mount and trigger listeners even when an error is thrown', () =
expect(listener).toHaveBeenCalledOnce()
})
})

it('should use the correct pending on unmount', () => {
const store = createStore()
const a = atom(0)
const b = atom(0, (_, set, update: number) => set(a, update))
b.onMount = (setAtom) => () => setAtom(1)
const aListener = vi.fn()
store.sub(a, aListener)
const unsub = store.sub(b, () => {})
aListener.mockClear()
unsub()
expect(store.get(a)).toBe(1)
expect(aListener).toHaveBeenCalledTimes(1)
})

0 comments on commit 0f0e1a2

Please sign in to comment.