Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(core): Unmount an atom that is no longer dependent within a derived atom #2660

Merged
merged 6 commits into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
})