Repository navigation
fix(store): keep computed atom subscriptions alive when the getter throws #428
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| --- | ||
| '@tanstack/store': patch | ||
| '@tanstack/react-store': patch | ||
| '@tanstack/preact-store': patch | ||
| --- | ||
|
|
||
| Keep computed atom subscriptions active when a getter throws. Notify observers through their optional error handler, rethrow the cached error on reads, and resume value notifications when the getter recovers. | ||
|
|
||
| Notify mounted React and Preact selectors when a computed getter throws so the nearest error boundary can render its fallback. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -157,6 +157,7 @@ export function createAtom<T>( | |
| ): Atom<T> | ReadonlyAtom<T> { | ||
| const isComputed = typeof valueOrFn === 'function' | ||
| const getter = valueOrFn as (prev?: T) => T | ||
| let computedError: { error: unknown } | undefined | ||
|
|
||
| // Create plain object atom | ||
| const atom: InternalAtom<T> = { | ||
|
|
@@ -175,18 +176,29 @@ export function createAtom<T>( | |
| return atom._snapshot | ||
| }, | ||
|
|
||
| subscribe(observerOrFn: Observer<T> | ((value: T) => void)) { | ||
| const obs = toObserver(observerOrFn) | ||
| subscribe( | ||
| observerOrFn: Observer<T> | ((value: T) => void), | ||
| onError?: Observer<T>['error'], | ||
| ) { | ||
| const obs = toObserver(observerOrFn, onError) | ||
| const observed = { current: false } | ||
| const e = effect(() => { | ||
| atom.get() | ||
| let value: T | ||
| try { | ||
| value = atom.get() | ||
| } catch (error) { | ||
| observed.current = true | ||
| activeSub = undefined | ||
| obs.error?.(error) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A dependency update inside the initial When the initial getter throws, Later updates to that dependency then stop at the dirty computed atom. The subscriber receives no further Required behavior: a dependency update made during the initial
|
||
| return | ||
| } | ||
| if (!observed.current) { | ||
| observed.current = true | ||
| } else { | ||
| // Observer reads must not become dependencies of the subscription. | ||
| // The enclosing effect restores activeSub in its finally block. | ||
| activeSub = undefined | ||
| obs.next?.(atom._snapshot) | ||
| obs.next?.(value) | ||
| } | ||
| }) | ||
|
|
||
|
|
@@ -213,17 +225,27 @@ export function createAtom<T>( | |
| } | ||
| try { | ||
| const oldValue = atom._snapshot | ||
| const newValue = | ||
| typeof getValue === 'function' | ||
| ? (getValue as (snapshot: T) => T)(oldValue) | ||
| : getValue === undefined && isComputed | ||
| ? getter(oldValue) | ||
| : getValue! | ||
| if (oldValue === undefined || !compare(oldValue, newValue)) { | ||
| let newValue: T | ||
| if (getValue === undefined) { | ||
| try { | ||
| newValue = getter(oldValue) | ||
| } catch (error) { | ||
| computedError = { error } | ||
| return true | ||
| } | ||
| } else { | ||
| newValue = | ||
| typeof getValue === 'function' | ||
| ? (getValue as (snapshot: T) => T)(oldValue) | ||
| : getValue | ||
| } | ||
| const changed = oldValue === undefined || !compare(oldValue, newValue) | ||
| if (changed) { | ||
| atom._snapshot = newValue | ||
| return true | ||
| } | ||
| return false | ||
| const recovered = computedError !== undefined | ||
| computedError = undefined | ||
| return changed || recovered | ||
| } finally { | ||
| activeSub = prevSub | ||
| if (isComputed) { | ||
|
|
@@ -251,6 +273,9 @@ export function createAtom<T>( | |
| if (activeSub !== undefined) { | ||
| link(atom, activeSub, cycle) | ||
| } | ||
| if (computedError !== undefined) { | ||
| throw computedError.error | ||
| } | ||
| return atom._snapshot | ||
| } | ||
| } else { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| import { describe, expect, test, vi } from 'vitest' | ||
| import { createAtom, createStore } from '../src' | ||
|
|
||
| function setup(initialValue = 1) { | ||
| const input = createAtom(initialValue) | ||
| const error = new Error('negative') | ||
| const getter = vi.fn(() => { | ||
| const value = input.get() | ||
| if (value < 0) { | ||
| throw error | ||
| } | ||
| return value * 2 | ||
| }) | ||
| return { input, computed: createAtom(getter), getter, error } | ||
| } | ||
|
|
||
| describe('computed atom errors', () => { | ||
| test('reports a getter error to observers without throwing from set()', () => { | ||
| const { input, computed, error } = setup() | ||
| const next = vi.fn() | ||
| const onError = vi.fn() | ||
| const subscription = computed.subscribe({ next, error: onError }) | ||
| try { | ||
| expect(() => input.set(-1)).not.toThrow() | ||
| expect(onError).toHaveBeenCalledTimes(1) | ||
| expect(onError.mock.calls[0]?.[0]).toBe(error) | ||
| expect(next).not.toHaveBeenCalled() | ||
| } finally { | ||
| subscription.unsubscribe() | ||
| } | ||
| }) | ||
|
|
||
| test.each(['atom', 'store'])( | ||
| 'reports getter errors to a separate callback for a computed %s', | ||
| (sourceType) => { | ||
| const { input, getter, error } = setup() | ||
| const source = | ||
| sourceType === 'atom' ? createAtom(getter) : createStore(getter) | ||
| const next = vi.fn() | ||
| const onError = vi.fn() | ||
| const subscription = source.subscribe(next, onError) | ||
| try { | ||
| input.set(-1) | ||
| expect(onError).toHaveBeenCalledExactlyOnceWith(error) | ||
| expect(next).not.toHaveBeenCalled() | ||
| input.set(2) | ||
| expect(next).toHaveBeenCalledExactlyOnceWith(4) | ||
| } finally { | ||
| subscription.unsubscribe() | ||
| } | ||
| }, | ||
| ) | ||
|
|
||
| test('notifies subscribers again even when a computed dependency recovers to the same value', () => { | ||
| const { input, computed, error } = setup() | ||
| const derived = createAtom(() => computed.get() + 1) | ||
| const next = vi.fn() | ||
| const subscription = derived.subscribe(next) | ||
| try { | ||
| try { | ||
| input.set(-1) | ||
| } catch (caught) { | ||
| expect(caught).toBe(error) | ||
| } | ||
| input.set(1) | ||
| expect(derived.get()).toBe(3) | ||
| input.set(2) | ||
| expect(next.mock.calls).toEqual([[3], [5]]) | ||
| } finally { | ||
| subscription.unsubscribe() | ||
| } | ||
| }) | ||
|
|
||
| test('throws on every read after invalidation, until the input recovers', () => { | ||
| const { input, computed, getter, error } = setup() | ||
| expect(computed.get()).toBe(2) | ||
|
|
||
| input.set(-1) | ||
| expect(() => computed.get()).toThrow(error) | ||
| expect(() => computed.get()).toThrow(error) | ||
| expect(getter).toHaveBeenCalledTimes(2) | ||
|
|
||
| input.set(2) | ||
| expect(computed.get()).toBe(4) | ||
| }) | ||
|
|
||
| test('caches an initial error and notifies a new subscriber when the getter recovers', () => { | ||
| const { input, computed, getter, error } = setup(-1) | ||
| expect(() => computed.get()).toThrow(error) | ||
| expect(() => computed.get()).toThrow(error) | ||
| expect(getter).toHaveBeenCalledTimes(1) | ||
|
|
||
| const next = vi.fn() | ||
| const onError = vi.fn() | ||
| const subscription = computed.subscribe({ next, error: onError }) | ||
| try { | ||
| expect(onError).toHaveBeenCalledWith(error) | ||
| expect(next).not.toHaveBeenCalled() | ||
| input.set(1) | ||
| expect(next).toHaveBeenCalledWith(2) | ||
| } finally { | ||
| subscription.unsubscribe() | ||
| } | ||
| }) | ||
| }) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Confirmed and fixed in 4adc5f2. React and Preact now send computed errors through the same subscription change handler, and new regression tests check that a mounted selector reaches the error boundary without an unrelated rerender.