From eb72c7fab63edaba536c240ab89b695e1c933254 Mon Sep 17 00:00:00 2001 From: David Maskasky Date: Thu, 14 Nov 2024 12:37:14 -0800 Subject: [PATCH] fix: rethrow falsy errors thrown in flushPending --- src/vanilla/store.ts | 10 +++++----- tests/vanilla/store.test.tsx | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/src/vanilla/store.ts b/src/vanilla/store.ts index 3684c00e65c..215ef8948f5 100644 --- a/src/vanilla/store.ts +++ b/src/vanilla/store.ts @@ -199,13 +199,13 @@ const addPendingFunction = (pending: Pending, fn: () => void) => { } const flushPending = (pending: Pending) => { - let error: unknown | undefined + const ref: { e?: AnyError } = {} const call = (fn: () => void) => { try { fn() } catch (e) { - if (!error) { - error = e + if (!('e' in ref)) { + ref.e = e } } } @@ -218,8 +218,8 @@ const flushPending = (pending: Pending) => { atomStates.forEach((atomState) => atomState.m?.l.forEach(call)) functions.forEach(call) } - if (error) { - throw error + if ('e' in ref) { + throw ref.e } } diff --git a/tests/vanilla/store.test.tsx b/tests/vanilla/store.test.tsx index 8a765240a06..9905909ea8a 100644 --- a/tests/vanilla/store.test.tsx +++ b/tests/vanilla/store.test.tsx @@ -876,3 +876,23 @@ describe('should mount and trigger listeners even when an error is thrown', () = expect(listener).toHaveBeenCalledOnce() }) }) + +it('throws falsy errors in onMount, onUnmount, and listeners', () => { + const store = createStore() + const a = atom(0) + a.onMount = () => { + throw '' + } + expect(() => store.sub(a, () => {})).toThrow('') + const b = atom(0) + b.onMount = () => () => { + throw '' + } + const unsub = store.sub(b, () => {}) + expect(() => unsub()).toThrow('') + const c = atom(0) + store.sub(c, () => { + throw '' + }) + expect(() => store.set(c, 1)).toThrow('') +})