Skip to content

Commit

Permalink
fix: rethrow falsy errors thrown in flushPending (#2820)
Browse files Browse the repository at this point in the history
  • Loading branch information
dmaskasky authored Nov 15, 2024
1 parent d9091a1 commit 0f05df8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 3 deletions.
8 changes: 5 additions & 3 deletions src/vanilla/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,13 +199,15 @@ const addPendingFunction = (pending: Pending, fn: () => void) => {
}

const flushPending = (pending: Pending) => {
let error: unknown | undefined
let error: AnyError
let hasError = false
const call = (fn: () => void) => {
try {
fn()
} catch (e) {
if (!error) {
if (!hasError) {
error = e
hasError = true
}
}
}
Expand All @@ -218,7 +220,7 @@ const flushPending = (pending: Pending) => {
atomStates.forEach((atomState) => atomState.m?.l.forEach(call))
functions.forEach(call)
}
if (error) {
if (hasError) {
throw error
}
}
Expand Down
20 changes: 20 additions & 0 deletions tests/vanilla/store.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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('')
})

0 comments on commit 0f05df8

Please sign in to comment.