Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/atom-compare-undefined.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/store': patch
---

Fix atoms skipping `compare` whenever their previous value was `undefined`. A computed atom that keeps returning `undefined` no longer notifies its subscribers on every recompute, and a custom `compare` now decides updates from an `undefined` value too. A computed atom's first computation still skips `compare`.
4 changes: 3 additions & 1 deletion packages/store/src/atom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 isFirstComputation = isComputed

// Create plain object atom
const atom: InternalAtom<T> = {
Expand Down Expand Up @@ -219,7 +220,8 @@ export function createAtom<T>(
: getValue === undefined && isComputed
? getter(oldValue)
: getValue!
if (oldValue === undefined || !compare(oldValue, newValue)) {
if (isFirstComputation || !compare(oldValue, newValue)) {
isFirstComputation = false
atom._snapshot = newValue
return true
}
Expand Down
42 changes: 42 additions & 0 deletions packages/store/tests/undefined-snapshot.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { describe, expect, test, vi } from 'vitest'
import { createAtom } from '../src'

describe('undefined snapshots', () => {
test('a computed atom that stays undefined does not notify', () => {
const source = createAtom(0)
const derived = createAtom(() =>
source.get() > 10 ? source.get() : undefined,
)
const fn = vi.fn()
derived.subscribe(fn)

source.set(1)
source.set(2)

expect(fn).not.toHaveBeenCalled()
})

test('compare still decides when the previous value is undefined', () => {
const atom = createAtom<number | undefined>(undefined, {
compare: () => true,
})
const fn = vi.fn()
atom.subscribe(fn)

atom.set(1)

expect(atom.get()).toBeUndefined()
expect(fn).not.toHaveBeenCalled()
})

test('compare is not called before a computed atom first computes', () => {
const source = createAtom(0)
const compare = vi.fn(
(prev: Array<number>, next: Array<number>) => prev.length === next.length,
)
const derived = createAtom(() => [source.get()], { compare })

expect(derived.get()).toEqual([0])
expect(compare).not.toHaveBeenCalled()
})
})