Skip to content

Commit

Permalink
fix(core): Unmount an atom that is no longer dependent within a deriv…
Browse files Browse the repository at this point in the history
…ed atom (#2660)

* Add test

* fix #2658

* refactor

---------

Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>
Co-authored-by: daishi <daishi@axlight.com>
  • Loading branch information
3 people authored Jul 23, 2024
1 parent 27117bf commit 98e23c9
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/vanilla/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -594,9 +594,9 @@ export const createStore = (): Store => {
}
for (const a of atomState.m.d || []) {
if (!atomState.d.has(a)) {
atomState.m.d.delete(a)
const aMounted = unmountAtom(pending, a)
aMounted?.t.delete(atom)
atomState.m.d.delete(a)
}
}
}
Expand Down Expand Up @@ -645,7 +645,7 @@ export const createStore = (): Store => {
if (
atomState.m &&
!atomState.m.l.size &&
!Array.from(atomState.m.t).some((a) => getAtomState(a).m)
!Array.from(atomState.m.t).some((a) => getAtomState(a).m?.d.has(atom))
) {
// unmount self
const onUnmount = atomState.m.u
Expand Down
17 changes: 17 additions & 0 deletions tests/vanilla/store.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -555,3 +555,20 @@ describe('aborting atoms', () => {
expect(callAfterAbort).toHaveBeenCalledTimes(1)
})
})

it('Unmount an atom that is no longer dependent within a derived atom (#2658)', async () => {
const condAtom = atom(true)

const baseAtom = atom(0)
const onUnmount = vi.fn()
baseAtom.onMount = () => onUnmount

const derivedAtom = atom((get) => {
if (get(condAtom)) get(baseAtom)
})

const store = createStore()
store.sub(derivedAtom, () => {})
store.set(condAtom, false)
expect(onUnmount).toHaveBeenCalledTimes(1)
})

0 comments on commit 98e23c9

Please sign in to comment.