Skip to content

Commit

Permalink
fix: rethrow falsy errors thrown in flushPending
Browse files Browse the repository at this point in the history
  • Loading branch information
dmaskasky committed Nov 14, 2024
1 parent d9091a1 commit eb72c7f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
10 changes: 5 additions & 5 deletions src/vanilla/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}
}
Expand All @@ -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
}
}

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 eb72c7f

Please # to comment.