From a647436bf7d50e49e0354e5292f4b34a4d95f6da Mon Sep 17 00:00:00 2001 From: nogaten <32513694+nogaten@users.noreply.github.com> Date: Mon, 15 Jul 2024 18:09:58 +0900 Subject: [PATCH 1/3] Add test --- tests/vanilla/store.test.tsx | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/tests/vanilla/store.test.tsx b/tests/vanilla/store.test.tsx index 652a551ca4..1c9e6d212f 100644 --- a/tests/vanilla/store.test.tsx +++ b/tests/vanilla/store.test.tsx @@ -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) +}) From 3fa5b7736eedaf3f7137160be07ad0c1c68aa6b0 Mon Sep 17 00:00:00 2001 From: nogaten <32513694+nogaten@users.noreply.github.com> Date: Sat, 20 Jul 2024 22:48:56 +0900 Subject: [PATCH 2/3] fix #2658 --- src/vanilla/store.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/vanilla/store.ts b/src/vanilla/store.ts index 49688c1c94..5e88fca29d 100644 --- a/src/vanilla/store.ts +++ b/src/vanilla/store.ts @@ -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) } } } @@ -645,7 +645,9 @@ 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) ?? false, + ) ) { // unmount self const onUnmount = atomState.m.u From 738f51e553ac11404834e458a7f808ee8394dc2a Mon Sep 17 00:00:00 2001 From: daishi Date: Sun, 21 Jul 2024 09:00:47 +0900 Subject: [PATCH 3/3] refactor --- src/vanilla/store.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/vanilla/store.ts b/src/vanilla/store.ts index 5e88fca29d..8081c8ecc4 100644 --- a/src/vanilla/store.ts +++ b/src/vanilla/store.ts @@ -645,9 +645,7 @@ export const createStore = (): Store => { if ( atomState.m && !atomState.m.l.size && - !Array.from(atomState.m.t).some( - (a) => getAtomState(a).m?.d.has(atom) ?? false, - ) + !Array.from(atomState.m.t).some((a) => getAtomState(a).m?.d.has(atom)) ) { // unmount self const onUnmount = atomState.m.u