Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

CHANGELOG.md

1,683 lines96.7 KB

@tanstack/react-db

1.0.0-rc.1

Major Changes

  • Release the first 1.0 candidate. Remove deprecated pre-1.0 APIs and give (#2171) published row metadata precedence over colliding selected fields. Structured source spreads and direct source-row returns keep source attribution; new functional objects and other projections receive output Collection metadata. Keep the two packages accidentally released as stable 1.x on their stable release lines. Both stable minor releases require @tanstack/db@^1.0.0-rc.0 for the RC health and restoration settlement APIs; upgrade DB with them.

    Remove Query Collection’s automatic refetch after mutation handlers. Handlers return Promise<void> and must await collection.utils.refetch() or write confirmed data with the write* utilities; { refetch: false } is removed.

Minor Changes

  • Breaking (1.0): a live query whose IR has no stable identity, such as one using fn.where, fn.select, or fn.having, now throws UnhashableQueryIRError unless it supplies a nonempty queryKey. It previously warned in development and kept its first compilation. An empty queryKey now counts as none, as it already did for a DbClient preload, so a hook and a preload agree on the query's identity. A dependency array does not replace queryKey: in that mode the hook checks identity and claims source Collection IDs each time it binds a live query, including one that useLiveSuspenseQuery takes from its cache. A reused source Collection ID now throws SourceCollectionIdReuseError. (#2235)

    A rejected render now releases every sync start it deferred for a DbClient descriptor, so a later hook or startSyncImmediate() can start that source. A render that never commits, because a sibling threw or it suspended, releases them when its live query is reclaimed.

  • Collections now answer two questions separately: can the data be shown (status), and is it still kept up to date (health). Once a query has shown data, a network or backend failure never takes it off the screen. (#2168)

    • status gains crashed: local storage broke (a closed IndexedDB connection, a failed SQLite persistence write or restore, a throwing sync function, or an invariant failure). Nothing recovers it in place, and reload() rejects. To recover, call cleanup({ dependents: true }), then start the Collection again (for example with preload()); it starts with no rows. It reaches every live query and Effect above it. error now means only "the first load failed".
    • Every Collection has collection.health, a health node with status, failureReason (the adapter is still trying), error (the adapter stopped, or the first load failed), reloading, and hasErrors. A live query's health has one node per source alias, in query order, and keeps object identity while unchanged. health:change fires when it changes. findProblems(health) lists the nodes that have a problem, in query order. Each problem (HealthProblem) shows its newest failure in message, cause, and at, and lists every failure still open in errors, oldest first: each reportError() of the sync run until reportHealthy(), or each failed request for more data on a live query's node. One error value is one failure: reporting it again changes nothing, and reportHealthy(error) removes just that failure, so a query Collection whose failing Query recovers removes only that Query's failures. After a live query is ready, a failed request for more data (a page, a joined row, or a source reload's replay of its data) is an error on the query's own node; the source stays healthy.
    • collection.reload() starts a new sync run and keeps the rows, status, and error on screen until the reload completes: when the new run's snapshot (begin({ snapshot: true })) or truncate() applies, or at its markReady(), which keeps the rows when no snapshot came. On a live query it reloads every Collection below it that shows an error, through nested live queries, then the query itself when its own node has an error, including a failed request for more data. It rejects on a crashed Collection. When the cleanup of the sync run that a reload retired rejects, the Collection crashes, also if the rejection comes later. A query in error stays there until its reload().
    • cleanup() rejects with CollectionHasSubscribersError while a live query with subscribers or an Effect reads the Collection. cleanup({ dependents: true }) ends them first. collection.subscribers lists every dependent.
    • A local-only Collection's reload() keeps its rows, including the user's writes: initialData loads only when the Collection starts, or starts again after cleanup.
    • Persisted Collections have one status. With initialRender: { strategy: 'network-first' }, restored rows make the Collection ready once the deadline passes or the remote fails; an empty restore stays loading. Only a local storage failure crashes a persisted Collection: a failed remote subset request is a failure reason, which the next successful remote request clears.

    Breaking changes and migration:

    BeforeAfter
    hook isErrorisLoadingError (first load failed) or isCrashed
    —isSyncError: ready and the health tree has a problem
    status: 'error' after a crashstatus: 'crashed'
    adapter markError(error)fail(error). After readiness it sets the node's error and keeps the rows. Later calls throw.
    cleanup() then preload() to recoverreload()
    adapter begin({ direct: true })begin(): every write applies on the rows the Collection holds, also during a reload
    a reload's first commit replaced every rowbegin({ snapshot: true }) or truncate() in the new run replaces them
    adapter markReady() after fail() threwit does nothing
    cleanup() while live queries or Effects read the Collectionrejects; unmount first or pass { dependents: true }
    persistedStatus, isPersistedReady, persistedError, preloadForInitialRender(), PERSISTED_READINESSstatus and health
    query-db utils.lastError, utils.isError, utils.errorCount, utils.clearError()collection.health, reload()
    infinite-query hooks' error (React, Preact, Vue, Svelte)the root node's error in health; fetchNextPage() still resolves

    Custom sync adapters: keep the run's readiness in your sync function. A reload calls sync again while collection.status still shows the previous run's status and the Collection still holds the previous run's rows. The new run's writes apply on those rows; it replaces every row only with a snapshot, a transaction begun with begin({ snapshot: true }), or with its own truncate(). The reload completes when that replacement applies, or at the new run's markReady(), which keeps the rows when no snapshot came. So send the new run's full state as a snapshot, or write against the kept rows: an insert of a key the Collection holds throws DuplicateKeySyncError, during a reload as at any time, so write update for a kept row, also from a replayed load after the reload completed. A reload keeps every row its new run does not rewrite: core never deletes kept rows on its own, so removing a row the backend deleted is the adapter's job, through a snapshot, a delete, or row ownership (#2269). An on-demand loadSubset result is partial and is never a snapshot. A live query's own reload keeps its rows and its window until its new run's result is complete. reportError() and reportHealthy() throw before the first markReady() and after fail(). markReady() after the run is ready, or after its fail(), does nothing, so an adapter needs no flag of its own to guard it. A second fail() in the same sync run does nothing. A first-ready callback that throws while sync runs is reported uncaught, and the Collection stays ready. reload() called from inside sync or a loadSubset call rejects, unless a reload is already in flight, whose promise it returns. Calls after a crash do nothing. For an on-demand Collection, a reload aborts the retired run's loadSubset calls and asks the new run's loadSubset for the current demand as soon as sync returns. Honor the signal: when core aborts a load, that load is over for core, and its later resolve or reject decides nothing, holds no readiness, and no replay waits for it. A loadSubset that throws synchronously is a rejection: a failed load, which requestSnapshot() and setWindow() report without throwing. A truncate's or reload's replay decides every request error of the query's demand: its success clears them all, and its failure replaces them with the replay's failures. useLiveSuspenseQuery now throws an Error for a failed first load or a crash: the cause itself when it is an Error, otherwise an Error with the problem's message whose cause holds the reported value.

Patch Changes

  • Breaking: grouping, includes, and pooling are now opt-in. An app bundles an operator's code only when it imports the value for that operator. Joins do not change. A typical app is about 8 kB smaller after gzip. This app has a query collection, a filtered live query, and React useLiveQuery. (#2232)

    • An include needs include(), toArray(), or materialize(). Change issues: q.from(...) in select() to issues: include(q.from(...)). A subquery in select() without one of these throws IncludeOperatorRequiredError.
    • Aggregates such as count() need no change. A groupBy with no aggregate takes groupKeys(): .groupBy(groupKeys(({ todo }) => todo.status)). Without it, the query throws GroupingOperatorRequiredError.
    • Hooks do not pool live queries by default. To share one partition among many equality-filtered queries, pass pool: pooledLiveQueries in the hook's query config: useLiveQuery({ query, pool: pooledLiveQueries }). Results do not change. Angular's { params, query } form takes pool the same way. Any other pool value, such as the old boolean, throws InvalidPoolOptionError, also for a disabled query. For adapter authors: the pool option of resolveLiveQueryValue is now pooledLiveQueries or false, not a boolean. An adapter that reads pool from its own options checks it with configPool first.
    • Code that builds query IR by hand must supply the operator code. IR.Aggregate takes groupingCompiler as its third argument. IR.IncludesSubquery takes includesRuntime as its fifth argument, before parentFilters. Import both from @tanstack/db. IR without them throws GroupingOperatorRequiredError or IncludeOperatorRequiredError when it compiles, unless another aggregate or groupKeys() in the query supplies the grouping compiler. Queries that the query builder builds need no change.
    • Operator code is part of query identity. A hook that re-renders a grouped query without groupKeys() now throws GroupingOperatorRequiredError. Before, React and Preact kept the grouped query.
    • Vue: when a changed query fails to compile, useLiveQuery no longer shows the rows of the previous query.
  • Production builds no longer include the development warnings of useLiveQuery. A typical app's bundle is about 1.6 kB smaller before compression and 0.66 kB smaller after gzip. (#2227)

  • Start the required Collection sync run when an ordinary subscriber follows an abandoned suspended render. Deferred acquisition still starts no idle source sync run or acquisition attempt. (#2229)

    Ordinary subscription admission and deferred acquisition resumption throw during cleanup, including automatic GC. Effects created then return disposed handles. Failed setup releases partial ownership, and throwing callbacks cannot prevent healthy observers receiving cleanup status. Subscribers surviving cleanup retain demand for an explicit restart.

    SSR captures each reader's rows and Collection status. Hydration preserves that view through browser preloads, runtime errors, sibling commits, and delayed streamed records. Missing records reject when transport ends. Known pending results survive normal record-stream close. A new stream after client cleanup starts independently of prior failures.

    Empty loading SSR needs no preload. Rendering rows or readiness requires matching query preparation or explicit source Collection preparation. Streaming Suspense prepares its result. Unsupported preparation throws with guidance. Prepared non-streaming Suspense remains supported. The DbClient query hash includes an infinite query's initial limit and offset.

    Apps without DbClient exclude its SSR implementation. Its API stays unchanged.

    Svelte roots initialized with hydrate() must set hydrating on DbProvider. Nested providers inherit it. Each provider clears initial hydration after mount so new children read live rows.

  • Updated dependencies [5649a07, 43d4ef6, 7538afd, a07cd73, 6c1ca8f, 30175be, 4c39add, 1640de8, 367ea7c, 7d9ed02, 45eeef8]:

    • @tanstack/db@1.0.0-rc.1

0.5.12

Patch Changes

0.5.11

Patch Changes

  • Keep usePacedMutations callbacks tied to the latest committed render so suspended transitions cannot mutate or persist another document's data. Refresh callbacks before descendant layout effects run while preserving the stable mutate function. (#2170)

  • Updated dependencies [468db85, 3c481f6, a09ba67, 92b11b0, fcd539a, 2c83fdc]:

    • @tanstack/db@0.15.1

0.5.10

Patch Changes

0.5.9

Patch Changes

  • Allow a Query built with Collection descriptors outside a DbClient to bind its sources when a client consumes it. Building or extending a query keeps descriptors unbound until that consumption. A reusable factory descriptor can now serve the same prebuilt query in separate client scopes, including React providers and server preloads. A prepared query is a bound snapshot; reuse the original unbound query across clients. The exported IR now represents an unbound descriptor with DescriptorRef; visitors of IR.From must handle the descriptorRef variant. (#2077)

    React hooks bind standalone descriptor queries through their DbProvider client and report a provider hint when no client is available. Svelte hooks bind through their client and release deferred sources after failed query setup.

  • Updated dependencies [cda9d6a, 2f928e6, dfec42e, 1a65c2c, 1b4ee8d, bbbf017, bc6f30e, fade2e2, bbe9327, b34a579, 6fa60aa, f84387c, be4a3d6, 0dc696a, fd13e3c]:

    • @tanstack/db@0.14.0

0.5.8

Patch Changes

0.5.7

Patch Changes

  • A live query no longer starts network work for its source collections before it has a subscriber or a preload. Rendering a component that never commits, or creating a live query with startSync: true, reads only the rows its sources already hold; the first subscriber or preload() starts the sources' sync and loads on-demand data. This applies to nested live queries and pooled eq queries too. useLiveSuspenseQuery preloads during render, so a source that already holds the rows still renders without suspending. A source collection's subscriberCount and subscribers:change now count only subscribers that ask for data, so a live query waiting for its first subscriber no longer makes a Query Collection refetch. (#2060)

  • Updated dependencies [487c5a6]:

    • @tanstack/db@0.12.3

0.5.6

Patch Changes

  • Fix useLiveInfiniteQuery showing an empty idle result on its first render for a synchronously loaded source. The hook now starts sync during render, as useLiveQuery does, so the first committed render already shows the ready first page instead of flashing empty content before data arrives. This applies to query callbacks and to supplied live query collections whose window is exactly the first page or has no limit. A supplied collection with a wider finite limit waits for the hook to narrow its window at commit, so it never requests rows the hook does not need. Renders that never commit are reclaimed by garbage collection, and a React 19 StrictMode double render reuses one collection instead of starting two. In React, a startup error from a replacement query still reaches the error boundary, and the hook rejects a source replaced by a different collection with the same ID while it is mounted, as useLiveQuery does. (#2027)

  • Updated dependencies [043c9b1, 25201da, 9e8ed99, 25201da, e753bc7]:

    • @tanstack/db@0.12.2

0.5.5

Patch Changes

  • Build a live query's keyed state map only when code reads it. Most callers read only data, so an update no longer builds a second copy of the results: (#2043)

    • The shared live query snapshot and the infinite query window build state on first read.
    • useLiveInfiniteQuery in React reads state only when your code reads it.
    • Vue and Svelte useLiveQuery build their data array from the snapshot's ordered rows instead of from state.

    A retained snapshot still shows the rows from the time it was built.

  • Updated dependencies [d029833, aa1b58e, c3a4e4a, 2376eb5, a37e69a, d029833, d029833, de8d0f1]:

    • @tanstack/db@0.12.1

0.5.4

Patch Changes

  • Reject a different source Collection that reuses an ID within one mounted derived live query. Keep separate Suspense queries bound to their own source Collections when the sources share an ID. (#2003)

  • Document common React skill mistakes: use expression helpers such as eq() in structured .where() predicates and destructure data from useLiveQuery() before rendering rows. (#1474)

  • Updated dependencies [2806da0, 7c516ce, eac6e8b, a21f4a4, cfb03f2]:

    • @tanstack/db@0.12.0

0.5.3

Patch Changes

  • Updated dependencies [06cab6f]:
    • @tanstack/db@0.11.3

0.5.2

Patch Changes

  • Run development-only checks in browser development builds. The duplicate @tanstack/db instance check and React's development warnings (deprecated dependency arrays, unhashable query identity) skipped themselves whenever there was no process global, which is the case in Vite and other browser bundles even though they inline process.env.NODE_ENV. They now read process.env.NODE_ENV as bundlers expect, so an app that loads two copies of @tanstack/db in development throws DuplicateDbInstanceError as documented. Set process.env.TANSTACK_DB_DISABLE_DUP_CHECK to '1' through your bundler's define to turn the check off. (#1987)

  • Mount and update many small filtered live queries at Redux-level cost. A live query that reads one eager source Collection, filters it by at least one eq(field, literal), and has no clause besides where and an orderBy on its own fields is served from an equality partition shared by every query on those fields, in React, Vue, Solid, Svelte, and Angular. Its other where conditions on the row, such as not, gt, or like, are evaluated per query over its group. This applies to a query function, a query builder, and a { query } config that sets no other option besides queryKey or gcTime. Queries with a DbClient (React, Svelte) or React Suspense keep a live-query Collection. Each query reads its group of rows instead of compiling a live query and subscribing to the source. With 240 such queries in React, mounting takes about 2.3 ms instead of 8.2 ms, and is the same with or without an index. (#1987)

    Results are unchanged: the same rows in the same order with the same values and status, including a terminal error when the source is cleaned up. Two things can differ. Rows are the source Collection's row objects rather than copies. The returned collection is built only when your code reads it, so its automatic id may differ, and tools that list live Collections do not see a pooled query until then.

  • Updated dependencies [dac687d, dac687d, dac687d, dac687d, 7595a2d, dac687d, dac687d, 8be6705]:

    • @tanstack/db@0.11.2

0.5.1

Patch Changes

0.5.0

Minor Changes

  • Add opt-in network-first initial rendering for eagerly persisted SQLite Collections. initialRender: { strategy: 'network-first', networkTimeoutMs } lets React and Solid Suspense render restored rows after the configured deadline (three seconds by default) or a network failure while sync continues. Live-query observers and the Angular, React, Solid, Svelte, and Vue integrations expose persistedStatus, isPersistedReady, and persistedError separately from Collection readiness. (#1955)

Patch Changes

  • Render completed persisted query data when a client query stream fails during network-first initial rendering. Keep derived-query load failures on the React ErrorBoundary, with errors isolated by client and cleared when the Collection restarts. (#1960)

  • Updated dependencies [9c62ac3, d5e4732, 0122da8, f7d96f7, fb509ef, dc4b4e0, f158258, c879ba6, b5d92ce]:

    • @tanstack/db@0.11.0

0.4.2

Patch Changes

0.4.1

Patch Changes

  • Updated dependencies [3c4c35d]:
    • @tanstack/db@0.9.2

0.4.0

Minor Changes

  • Remove the ignored getNextPageParam option from useLiveInfiniteQuery and reject it with a clear error when passed at runtime. Delete this callback from your config; for server pagination, use an on-demand Query Collection whose queryFn fulfills meta.loadSubsetOptions. Document fixed-server-page loading and clarify that initialPageParam labels result pages rather than setting a server cursor. (#1806)

Patch Changes

0.3.8

Patch Changes

  • Updated dependencies [cfb01ce]:
    • @tanstack/db@0.9.0

0.3.7

Patch Changes

  • Updated dependencies [bbc9edf]:
    • @tanstack/db@0.8.7

0.3.6

Patch Changes

  • Updated dependencies [ae2fe74]:
    • @tanstack/db@0.8.6

0.3.5

Patch Changes

0.3.4

Patch Changes

0.3.3

Patch Changes

  • Support disabling live queries declared with the { query } config syntax by returning undefined or null from the query callback. (#1757)

  • Updated dependencies [99ba511, 43cc741]:

    • @tanstack/db@0.8.3

0.3.2

Patch Changes

  • Updated dependencies [c521b5d]:
    • @tanstack/db@0.8.2

0.3.1

Patch Changes

0.3.0

Minor Changes

  • Add SSR through request-scoped DbClient instances, collection descriptors, (#1564) explicit collection-row hydration, live-query result snapshots, adapter sync metadata, and React and Svelte descriptor resolution.

    React live queries now derive identity from structured query IR. Opaque queries can provide queryKey; legacy dependency arrays and unkeyed opaque queries keep working with development warnings until 1.0.

    Add TanStack Router integration that streams live queries discovered during a Suspense render as pending promises which resolve to ordered result snapshots. The browser starts normal source sync and atomically replaces the snapshot when its live result is ready.

Patch Changes

  • Updated dependencies [4b9e8cd]:
    • @tanstack/db@0.8.0

0.2.1

Patch Changes

  • Update agent skills to match current APIs and behavior. (#1696)

  • Updated dependencies [5f63996]:

    • @tanstack/db@0.7.2

0.2.0

Minor Changes

  • Add useLiveInfiniteQuery as a Vue binding over the shared live-query window controller. Align infinite-query behavior across React, Vue, and Svelte, including awaitable page fetches, safe page sizes, reactive page-depth preservation, ordered collection validation, shared input resolution, and shared-window cleanup. (#1724)

Patch Changes

  • Updated dependencies [424382b]:
    • @tanstack/db@0.7.1

0.1.96

Patch Changes

  • Add an internal shared live-query observer and migrate all five framework adapters to it (#1642)

    Introduces createLiveQueryObserver in @tanstack/db: given a resolved live-query collection (or null for a disabled query) it owns the subscription lifecycle every adapter used to re-implement — change and status subscriptions, a snapshot with stable identity per state revision for wholesale consumers, and delivery of the raw ChangeMessage[] for granular consumers. React, Vue, Svelte, Solid, and Angular's live-query hooks now materialize from the observer instead of their own hand-rolled subscription/status/snapshot machinery, keeping each adapter's native reactivity and each adapter's data-loading policy (wholesale adapters subscribe without initial state; granular adapters seed from it).

    The observer is an internal, unstable contract for TanStack DB's official adapters — it is exported so the adapter packages can consume it, but it is not a public extension point yet and its API may change in any release.

    The migration also fixes several live-query lifecycle defects: status-only transitions (error, cleaned-up) now reach mounted consumers; snapshot identity is stable across unsubscribe/resubscribe and stays fresh while detached; dispatch is FIFO and non-reentrant with subscriptions identified by record rather than callback; disposing during the synchronous initial replay no longer leaks the collection subscription; subscribing after dispose throws instead of registering a dead listener; Solid guards its async resource continuations against superseded collections; and constructing an observer no longer activates sync. Observers activate on their first committed subscription unless an adapter has already started a pre-created collection supplied directly or returned from a callback.

  • Add the unstable, internal createLiveQueryWindowController primitive for (#1675) forward pagination. It coordinates collection-scoped window leases, commits pages only after subset loads succeed, restores windows after failures and cleanup, and lets React's useLiveInfiniteQuery become a thin binding without changing its public API or resetting pages for structurally equal dependencies.

  • Updated dependencies [ad88d07, 7e7abda, dc53f0e]:

    • @tanstack/db@0.7.0

0.1.95

Patch Changes

  • Updated dependencies [8ee783d]:
    • @tanstack/db@0.6.17

0.1.94

Patch Changes

0.1.93

Patch Changes

  • Extract shared live-query adapter helpers into @tanstack/db (#1641)

    Adds isCollection, isSingleResultCollection, and getLiveQueryStatusFlags to @tanstack/db and migrates all five framework adapters to use them. isCollection replaces the per-adapter duck-typing and Solid's instanceof CollectionImpl with one structural, multi-realm-safe guard (the instanceof form gave false negatives across dual-package boundaries). No behavior change; internal deduplication only.

  • Updated dependencies [eabcea7, 6d4c096]:

    • @tanstack/db@0.6.15

0.1.92

Patch Changes

  • Updated dependencies [397e12a]:
    • @tanstack/db@0.6.14

0.1.91

Patch Changes

0.1.90

Patch Changes

  • Updated dependencies [2b27dd1]:
    • @tanstack/db@0.6.12

0.1.89

Patch Changes

0.1.88

Patch Changes

  • Updated dependencies [307fdf8]:
    • @tanstack/db@0.6.10

0.1.87

Patch Changes

0.1.86

Patch Changes

  • Updated dependencies [3827b62]:
    • @tanstack/db@0.6.8

0.1.85

Patch Changes

0.1.84

Patch Changes

  • Updated dependencies [4e9ab39]:
    • @tanstack/db@0.6.6

0.1.83

Patch Changes

0.1.82

Patch Changes

  • Add includes (hierarchical data) documentation to all framework SKILL.md files and fix inaccurate toArray scalar select constraint in db-core/live-queries skill. (#1361)

  • Updated dependencies [1e69dd6]:

    • @tanstack/db@0.6.4

0.1.81

Patch Changes

0.1.80

Patch Changes

  • Fix stale status mismatch in useLiveSuspenseQuery causing infinite suspense fallback. (#1427)

  • Updated dependencies [3fe689a, c314c36]:

    • @tanstack/db@0.6.2

0.1.79

Patch Changes

  • Update all SKILL.md files to v0.6.0 with new documentation for persistence, virtual properties, queryOnce, createEffect, includes, indexing, and sync metadata. Add tanstack-intent keyword to all packages with skills. (#1421)

  • Updated dependencies [8b7fb1a]:

    • @tanstack/db@0.6.1

0.1.78

Patch Changes

0.1.77

Patch Changes

  • Add createEffect API for reactive delta-driven effects and useLiveQueryEffect React hook. (#1221)

    createEffect attaches callbacks to a live query's delta stream — firing onEnter, onExit, and onUpdate for row-level query-result transitions and onBatch for the full delta batch from each graph run — without materialising the full result set. Supports skipInitial, orderBy + limit (top-K window), joins, lazy loading, transaction coalescing, async disposal with AbortSignal, and onSourceError / onError callbacks.

    useLiveQueryEffect is the React hook wrapper that manages the effect lifecycle (create on mount, dispose on unmount, recreate on dependency change).

  • Updated dependencies [c3e6a96]:

    • @tanstack/db@0.5.33

0.1.76

Patch Changes

0.1.75

Patch Changes

  • Add Intent agent skills (SKILL.md files) to guide AI coding agents. Include skills for core DB concepts, all 5 framework bindings, meta-framework integration, and offline transactions. Also add export * from '@tanstack/db' to angular-db for consistency with other framework packages. (#1330)

  • fix(react-db): make getNextPageParam optional in useLiveInfiniteQuery (#1268)

  • fix(react-db): handle rejected/stale setWindow promises in useLiveInfiniteQuery (#1269)

  • Updated dependencies [bf1d078]:

    • @tanstack/db@0.5.31

0.1.74

Patch Changes

  • Updated dependencies [e9d0fd8]:
    • @tanstack/db@0.5.30

0.1.73

Patch Changes

0.1.72

Patch Changes

  • Updated dependencies [46450e7]:
    • @tanstack/db@0.5.28

0.1.71

Patch Changes

0.1.70

Patch Changes

  • Fix useLiveInfiniteQuery peek-ahead detection for hasNextPage. The initial query now correctly requests pageSize + 1 items to detect whether additional pages exist, matching the behavior of subsequent page loads. (#1209)

    Fix async on-demand pagination by ensuring the graph callback fires at least once even when there is no pending graph work, so that loadMoreIfNeeded is triggered after setWindow() increases the limit.

  • Updated dependencies [85c373e, 9184dcc, 83d5ac8]:

    • @tanstack/db@0.5.26

0.1.69

Patch Changes

0.1.68

Patch Changes

  • Updated dependencies [7099459]:
    • @tanstack/db@0.5.24

0.1.67

Patch Changes

  • Updated dependencies [05130f2]:
    • @tanstack/db@0.5.23

0.1.66

Patch Changes

  • Updated dependencies [f9b741e]:
    • @tanstack/db@0.5.22

0.1.65

Patch Changes

0.1.64

Patch Changes

  • Updated dependencies []:
    • @tanstack/db@0.5.20

0.1.63

Patch Changes

0.1.62

Patch Changes

  • Updated dependencies [c1247e8]:
    • @tanstack/db@0.5.18

0.1.61

Patch Changes

  • Improve runtime error message and documentation when useLiveSuspenseQuery receives undefined from query callback. (#860)

    Following TanStack Query's useSuspenseQuery design, useLiveSuspenseQuery intentionally does not support disabled queries (when callback returns undefined or null). This maintains the type guarantee that data is always T (not T | undefined), which is a core benefit of using Suspense.

    What changed:

    1. Improved runtime error message with clear guidance:
    useLiveSuspenseQuery does not support disabled queries (callback returned undefined/null).
    The Suspense pattern requires data to always be defined (T, not T | undefined).
    Solutions:
    1) Use conditional rendering - don't render the component until the condition is met.
    2) Use useLiveQuery instead, which supports disabled queries with the 'isEnabled' flag.
    1. Enhanced JSDoc documentation with detailed @remarks section explaining the design decision, showing both incorrect (❌) and correct (✅) patterns

    Why this matters:

    // ❌ This pattern doesn't work with Suspense queries:
    const { data } = useLiveSuspenseQuery(
      (q) => userId
        ? q.from({ users }).where(({ users }) => eq(users.id, userId)).findOne()
        : undefined,
      [userId]
    )
    
    // ✅ Instead, use conditional rendering:
    function UserProfile({ userId }: { userId: string }) {
      const { data } = useLiveSuspenseQuery(
        (q) => q.from({ users }).where(({ users }) => eq(users.id, userId)).findOne(),
        [userId]
      )
      return <div>{data.name}</div> // data is guaranteed non-undefined
    }
    
    function App({ userId }: { userId?: string }) {
      if (!userId) return <div>No user selected</div>
      return <UserProfile userId={userId} />
    }
    
    // ✅ Or use useLiveQuery for conditional queries:
    const { data, isEnabled } = useLiveQuery(
      (q) => userId
        ? q.from({ users }).where(({ users }) => eq(users.id, userId)).findOne()
        : undefined,
      [userId]
    )

    This aligns with TanStack Query's philosophy where Suspense queries prioritize type safety and proper component composition over flexibility.

  • Updated dependencies [f795a67, d542667, 6503c09, b1cc4a7]:

    • @tanstack/db@0.5.17

0.1.60

Patch Changes

  • Updated dependencies [41308b8]:
    • @tanstack/db@0.5.16

0.1.59

Patch Changes

  • Updated dependencies [32ec4d8]:
    • @tanstack/db@0.5.15

0.1.58

Patch Changes

  • Updated dependencies [26ed0aa]:
    • @tanstack/db@0.5.14

0.1.57

Patch Changes

0.1.56

Patch Changes

0.1.55

Patch Changes

  • Fixed isReady to return true for disabled queries in useLiveQuery/injectLiveQuery across all framework packages. When a query function returns null or undefined (disabling the query), there's no async operation to wait for, so the hook should be considered "ready" immediately. (#886)

    Additionally, all frameworks now have proper TypeScript overloads that explicitly support returning undefined | null from query functions, making the disabled query pattern type-safe.

    This fixes the common pattern where users conditionally enable queries and don't want to show loading states when the query is disabled.

  • Updated dependencies [c4b9399, a1a484e]:

    • @tanstack/db@0.5.11

0.1.54

Patch Changes

0.1.53

Patch Changes

  • Updated dependencies [5f474f1]:
    • @tanstack/db@0.5.9

0.1.52

Patch Changes

0.1.51

Patch Changes

  • Updated dependencies [295cb45]:
    • @tanstack/db@0.5.7

0.1.50

Patch Changes

  • Updated dependencies [c8a2c16]:
    • @tanstack/db@0.5.6

0.1.49

Patch Changes

  • Updated dependencies [077fc1a]:
    • @tanstack/db@0.5.5

0.1.48

Patch Changes

0.1.47

Patch Changes

0.1.46

Patch Changes

  • Updated dependencies [99a3716]:
    • @tanstack/db@0.5.2

0.1.45

Patch Changes

  • Updated dependencies [a83a818]:
    • @tanstack/db@0.5.1

0.1.44

Patch Changes

0.1.43

Patch Changes

0.1.42

Patch Changes

  • Updated dependencies [75470a8]:
    • @tanstack/db@0.4.19

0.1.41

Patch Changes

  • Add useLiveSuspenseQuery hook for React Suspense support (#697)

    Introduces a new useLiveSuspenseQuery hook that integrates with React Suspense and Error Boundaries, following TanStack Query's useSuspenseQuery pattern.

    Key features:

    • React 18+ compatible using the throw promise pattern
    • Type-safe API with guaranteed data (never undefined)
    • Automatic error handling via Error Boundaries
    • Reactive updates after initial load via useSyncExternalStore
    • Support for dependency-based re-suspension
    • Works with query functions, config objects, and pre-created collections

    Example usage:

    import { Suspense } from 'react'
    import { useLiveSuspenseQuery } from '@tanstack/react-db'
    
    function TodoList() {
      // Data is guaranteed to be defined - no isLoading needed
      const { data } = useLiveSuspenseQuery((q) =>
        q
          .from({ todos: todosCollection })
          .where(({ todos }) => eq(todos.completed, false)),
      )
    
      return (
        <ul>
          {data.map((todo) => (
            <li key={todo.id}>{todo.text}</li>
          ))}
        </ul>
      )
    }
    
    function App() {
      return (
        <Suspense fallback={<div>Loading...</div>}>
          <TodoList />
        </Suspense>
      )
    }

    Implementation details:

    • Throws promises when collection is loading (caught by Suspense)
    • Throws errors when collection fails (caught by Error Boundary)
    • Reuses promise across re-renders to prevent infinite loops
    • Detects dependency changes and creates new collection/promise
    • Same TypeScript overloads as useLiveQuery for consistency

    Documentation:

    • Comprehensive guide in live-queries.md covering usage patterns and when to use each hook
    • Comparison with useLiveQuery showing different approaches to loading/error states
    • Router loader pattern recommendation for React Router/TanStack Router users
    • Error handling examples with Suspense and Error Boundaries

    Resolves #692

0.1.40

Patch Changes

0.1.39

Patch Changes

  • Updated dependencies [49bcaa5]:
    • @tanstack/db@0.4.17

0.1.38

Patch Changes

  • Add paced mutations with pluggable timing strategies (#704)

    Introduces a new paced mutations system that enables optimistic mutations with pluggable timing strategies. This provides fine-grained control over when and how mutations are persisted to the backend. Powered by TanStack Pacer.

    Key Design:

    • Debounce/Throttle: Only one pending transaction (collecting mutations) and one persisting transaction (writing to backend) at a time. Multiple rapid mutations automatically merge together.
    • Queue: Each mutation creates a separate transaction, guaranteed to run in the order they're made (FIFO by default, configurable to LIFO).

    Core Features:

    • Pluggable Strategy System: Choose from debounce, queue, or throttle strategies to control mutation timing
    • Auto-merging Mutations: Multiple rapid mutations on the same item automatically merge for efficiency (debounce/throttle only)
    • Transaction Management: Full transaction lifecycle tracking (pending → persisting → completed/failed)
    • React Hook: usePacedMutations for easy integration in React applications

    Available Strategies:

    • debounceStrategy: Wait for inactivity before persisting. Only final state is saved. (ideal for auto-save, search-as-you-type)
    • queueStrategy: Each mutation becomes a separate transaction, processed sequentially in order (defaults to FIFO, configurable to LIFO). All mutations are guaranteed to persist. (ideal for sequential workflows, rate-limited APIs)
    • throttleStrategy: Ensure minimum spacing between executions. Mutations between executions are merged. (ideal for analytics, progress updates)

    Example Usage:

    import { usePacedMutations, debounceStrategy } from '@tanstack/react-db'
    
    const mutate = usePacedMutations({
      mutationFn: async ({ transaction }) => {
        await api.save(transaction.mutations)
      },
      strategy: debounceStrategy({ wait: 500 }),
    })
    
    // Trigger a mutation
    const tx = mutate(() => {
      collection.update(id, (draft) => {
        draft.value = newValue
      })
    })
    
    // Optionally await persistence
    await tx.isPersisted.promise
  • Updated dependencies [979a66f, f8a979b, cb25623]:

    • @tanstack/db@0.4.16

0.1.37

Patch Changes

  • Updated dependencies [6738247]:
    • @tanstack/db@0.4.15

0.1.36

Patch Changes

  • Updated dependencies [970616b]:
    • @tanstack/db@0.4.14

0.1.35

Patch Changes

  • Updated dependencies [3c9526c]:
    • @tanstack/db@0.4.13

0.1.34

Patch Changes

0.1.33

Patch Changes

  • Add support for pre-created live query collections in useLiveInfiniteQuery, enabling router loader patterns where live queries can be created, preloaded, and passed to components. (#684)

  • Updated dependencies [5566b26]:

    • @tanstack/db@0.4.11

0.1.32

Patch Changes

  • Add useLiveInfiniteQuery hook for infinite scrolling with live updates. (#669)

    The new useLiveInfiniteQuery hook provides an infinite query pattern similar to TanStack Query's useInfiniteQuery, but with live updates from your local collection. It uses liveQueryCollection.utils.setWindow() internally to efficiently paginate through ordered data without recreating the query on each page fetch.

    Key features:

    • Automatic live updates as data changes in the collection
    • Efficient pagination using dynamic window adjustment
    • Peek-ahead mechanism to detect when more pages are available
    • Compatible with TanStack Query's infinite query API patterns

    Example usage:

    import { useLiveInfiniteQuery } from '@tanstack/react-db'
    
    function PostList() {
      const { data, pages, fetchNextPage, hasNextPage, isLoading } =
        useLiveInfiniteQuery(
          (q) =>
            q
              .from({ posts: postsCollection })
              .orderBy(({ posts }) => posts.createdAt, 'desc'),
          {
            pageSize: 20,
            getNextPageParam: (lastPage, allPages) =>
              lastPage.length === 20 ? allPages.length : undefined,
          },
        )
    
      if (isLoading) return <div>Loading...</div>
    
      return (
        <div>
          {pages.map((page, i) => (
            <div key={i}>
              {page.map((post) => (
                <PostCard key={post.id} post={post} />
              ))}
            </div>
          ))}
          {hasNextPage && (
            <button onClick={() => fetchNextPage()}>Load More</button>
          )}
        </div>
      )
    }

    Requirements:

    • Query must include .orderBy() for the window mechanism to work
    • Returns flattened data array and pages array for flexible rendering
    • Automatically detects new pages when data is synced to the collection
  • Updated dependencies [63aa8ef, b0687ab]:

    • @tanstack/db@0.4.10

0.1.31

Patch Changes

0.1.30

Patch Changes

  • Refactored live queries to execute eagerly during sync. Live queries now materialize their results immediately as data arrives from source collections, even while those collections are still in a "loading" state, rather than waiting for all sources to be "ready" before executing. (#658)

  • Updated dependencies [d9ae7b7, 44555b7]:

    • @tanstack/db@0.4.8

0.1.29

Patch Changes

  • Updated dependencies [6692aad]:
    • @tanstack/db@0.4.7

0.1.28

Patch Changes

0.1.27

Patch Changes

  • Updated dependencies [7556fb6]:
    • @tanstack/db@0.4.5

0.1.26

Patch Changes

0.1.25

Patch Changes

  • Updated dependencies [32f2212]:
    • @tanstack/db@0.4.3

0.1.24

Patch Changes

0.1.23

Patch Changes

  • Updated dependencies [8cd0876]:
    • @tanstack/db@0.4.1

0.1.22

Patch Changes

  • Let collection.subscribeChanges return a subscription object. Move all data loading code related to optimizations into that subscription object. (#564)

  • Updated dependencies [2f87216, ac6250a, 2f87216]:

    • @tanstack/db@0.4.0

0.1.21

Patch Changes

  • Expand useLiveQuery callback to support conditional queries and additional return types, enabling the ability to temporarily disable the query. (#535)

    New Features:

    • Callback can now return undefined or null to temporarily disable the query
    • Callback can return a pre-created Collection instance to use it directly
    • Callback can return a LiveQueryCollectionConfig object for advanced configuration
    • When disabled (returning undefined/null), the hook returns a specific idle state

    Usage Examples:

    // Conditional queries - disable when not ready
    const enabled = useState(false)
    const { data, state, isIdle } = useLiveQuery((q) => {
      if (!enabled) return undefined  // Disables the query
      return q.from({ users }).where(...)
    }, [enabled])
    
    /**
     * When disabled, returns:
     * {
     *   state: undefined,
     *   data: undefined,
     *   isIdle: true,
     *   ...
     * }
     */
    
    // Return pre-created Collection
    const { data } = useLiveQuery((q) => {
      if (usePrebuilt) return myCollection  // Use existing collection
      return q.from({ items }).select(...)
    }, [usePrebuilt])
    
    // Return LiveQueryCollectionConfig
    const { data } = useLiveQuery((q) => {
      return {
        query: q.from({ items }).select(...),
        id: `my-collection`,
      }
    })
  • Updated dependencies [cacfca2]:

    • @tanstack/db@0.3.2

0.1.20

Patch Changes

  • Updated dependencies [5f51f35]:
    • @tanstack/db@0.3.1

0.1.19

Patch Changes

0.1.18

Patch Changes

0.1.17

Patch Changes

0.1.16

Patch Changes

  • Updated dependencies [b162556]:
    • @tanstack/db@0.2.3

0.1.15

Patch Changes

  • Updated dependencies [33515c6]:
    • @tanstack/db@0.2.2

0.1.14

Patch Changes

  • Updated dependencies [620ebea]:
    • @tanstack/db@0.2.1

0.1.13

Patch Changes

0.1.12

Patch Changes

  • Updated dependencies [cc4c34a]:
    • @tanstack/db@0.1.12

0.1.11

Patch Changes

  • Fixed a bug where a race condition could cause initial results not to be rendered when using useLiveQuery. (#485)

  • Updated dependencies [b869f68]:

    • @tanstack/db@0.1.11

0.1.10

Patch Changes

0.1.9

Patch Changes

  • Updated dependencies [d64b4a8]:
    • @tanstack/db@0.1.9

0.1.8

Patch Changes

0.1.7

Patch Changes

0.1.6

Patch Changes

  • Updated dependencies [ad33e9e]:
    • @tanstack/db@0.1.6

0.1.5

Patch Changes

  • ensure that useLiveQuery returns a stable ref when there are no changes (#388)

  • Updated dependencies [9a5a20c]:

    • @tanstack/db@0.1.5

0.1.4

Patch Changes

0.1.3

Patch Changes

  • Updated dependencies [0cb7699]:
    • @tanstack/db@0.1.3

0.1.2

Patch Changes

0.1.1

Patch Changes

0.1.0

Minor Changes

  • 0.1 release - first beta 🎉 (#332)

Patch Changes

  • We have moved development of the differential dataflow implementation from @electric-sql/d2mini to a new @tanstack/db-ivm package inside the tanstack db monorepo to make development simpler. (#330)

  • Updated dependencies [7d2f4be, f0eda36]:

    • @tanstack/db@0.1.0

0.0.33

Patch Changes

  • Updated dependencies [6e8d7f6]:
    • @tanstack/db@0.0.33

0.0.32

Patch Changes

  • Updated dependencies [e04bd12]:
    • @tanstack/db@0.0.32

0.0.31

Patch Changes

  • Updated dependencies [3e9a36d]:
    • @tanstack/db@0.0.31

0.0.30

Patch Changes

  • Updated dependencies [6bdde55]:
    • @tanstack/db@0.0.30

0.0.29

Patch Changes

0.0.28

Patch Changes

0.0.27

Patch Changes

  • Updated dependencies [bec8620]:
    • @tanstack/db@0.0.27

0.0.26

Patch Changes

  • Add initial release of TrailBase collection for TanStack DB. TrailBase is a blazingly fast, open-source alternative to Firebase built on Rust, SQLite, and V8. It provides type-safe REST and realtime APIs with sub-millisecond latencies, integrated authentication, and flexible access control - all in a single executable. This collection type enables seamless integration with TrailBase backends for high-performance real-time applications. (#228)

  • Updated dependencies [09c6995]:

    • @tanstack/db@0.0.26

0.0.25

Patch Changes

0.0.24

Patch Changes

0.0.23

Patch Changes

  • Updated dependencies [056609e]:
    • @tanstack/db@0.0.23

0.0.22

Patch Changes

  • Updated dependencies [aeee9a1]:
    • @tanstack/db@0.0.22

0.0.21

Patch Changes

  • Updated dependencies [8e23322]:
    • @tanstack/db@0.0.21

0.0.20

Patch Changes

  • Updated dependencies [f13c11e]:
    • @tanstack/db@0.0.20

0.0.19

Patch Changes

  • Updated dependencies [9f0b0c2]:
    • @tanstack/db@0.0.19

0.0.18

Patch Changes

  • Improve jsdocs (#243)

  • Updated dependencies [266bd29]:

    • @tanstack/db@0.0.18

0.0.17

Patch Changes

  • Updated dependencies [7e63d76]:
    • @tanstack/db@0.0.17

0.0.16

Patch Changes

  • add support for composable queries (#232)

  • Updated dependencies [e478d53]:

    • @tanstack/db@0.0.16

0.0.15

Patch Changes

0.0.14

Patch Changes

  • Updated dependencies [74c140d]:
    • @tanstack/db@0.0.14

0.0.13

Patch Changes

  • feat: implement Collection Lifecycle Management (#198)

    Adds automatic lifecycle management for collections to optimize resource usage.

    New Features:

    • Added startSync option (defaults to false, set to true to start syncing immediately)
    • Automatic garbage collection after gcTime (default 5 minutes) of inactivity
    • Collection status tracking: "idle" | "loading" | "ready" | "error" | "cleaned-up"
    • Manual preload() and cleanup() methods for lifecycle control

    Usage:

    const collection = createCollection({
      startSync: false, // Enable lazy loading
      gcTime: 300000, // Cleanup timeout (default: 5 minutes)
    })
    
    console.log(collection.status) // Current state
    await collection.preload() // Ensure ready
    await collection.cleanup() // Manual cleanup
  • Add createOptimisticAction helper that replaces useOptimisticMutation (#210)

    An example of converting a useOptimisticMutation hook to createOptimisticAction. Now all optimistic & server mutation logic are consolidated.

    -import { useOptimisticMutation } from '@tanstack/react-db'
    +import { createOptimisticAction } from '@tanstack/react-db'
    +
    +// Create the `addTodo` action, passing in your `mutationFn` and `onMutate`.
    +const addTodo = createOptimisticAction<string>({
    +  onMutate: (text) => {
    +    // Instantly applies the local optimistic state.
    +    todoCollection.insert({
    +      id: uuid(),
    +      text,
    +      completed: false
    +    })
    +  },
    +  mutationFn: async (text) => {
    +    // Persist the todo to your backend
    +    const response = await fetch('/api/todos', {
    +      method: 'POST',
    +      body: JSON.stringify({ text, completed: false }),
    +    })
    +    return response.json()
    +  }
    +})
    
     const Todo = () => {
    -  // Create the `addTodo` mutator, passing in your `mutationFn`.
    -  const addTodo = useOptimisticMutation({ mutationFn })
    -
       const handleClick = () => {
    -    // Triggers the mutationFn
    -    addTodo.mutate(() =>
    -      // Instantly applies the local optimistic state.
    -      todoCollection.insert({
    -        id: uuid(),
    -        text: '🔥 Make app faster',
    -        completed: false
    -      })
    -    )
    +    // Triggers the onMutate and then the mutationFn
    +    addTodo('🔥 Make app faster')
       }
    
       return <Button onClick={ handleClick } />
     }
  • Updated dependencies [945868e, 0f8a008, 57b5f5d]:

    • @tanstack/db@0.0.13

0.0.12

Patch Changes

  • Updated dependencies [f6abe9b]:
    • @tanstack/db@0.0.12

0.0.11

Patch Changes

  • Export ElectricCollectionUtils & allow passing generic to createTransaction (#179)

  • Updated dependencies [66ed58b, c5489ff]:

    • @tanstack/db@0.0.11

0.0.10

Patch Changes

  • Updated dependencies [38d4505]:
    • @tanstack/db@0.0.10

0.0.9

Patch Changes

  • Updated dependencies [2ae0b09]:
    • @tanstack/db@0.0.9

0.0.8

Patch Changes

  • A large refactor of the core Collection with: (#155)

    • a change to not use Store internally and emit fine grade changes with subscribeChanges and subscribeKeyChanges methods.
    • changes to the Collection api to be more Map like for reads, with get, has, size, entries, keys, and values.
    • renames config.getId to config.getKey for consistency with the Map like api.
  • Updated dependencies [5c538cf, 9553366, b4602a0, 02adc81, 06d8ecc, c50cd51]:

    • @tanstack/db@0.0.8

0.0.7

Patch Changes

  • Expose utilities on collection instances (#161)

    Implemented a utility exposure pattern for TanStack DB collections that allows utility functions to be passed as part of collection options and exposes them under a .utils namespace, with full TypeScript typing.

    • Refactored createCollection in packages/db/src/collection.ts to accept options with utilities directly
    • Added utils property to CollectionImpl
    • Added TypeScript types for utility functions and utility records
    • Changed Collection from a class to a type, updating all usages to use createCollection() instead
    • Updated Electric/Query implementations
    • Utilities are now ergonomically accessible under .utils
    • Full TypeScript typing is preserved for both collection data and utilities
    • API is clean and straightforward - users can call createCollection(optionsCreator(config)) directly
    • Zero-boilerplate TypeScript pattern that infers utility types automatically
  • Updated dependencies [8b43ad3]:

    • @tanstack/db@0.0.7

0.0.6

Patch Changes

0.0.5

Patch Changes

  • Collections must have a getId function & use an id for update/delete operators (#134)

  • the keyBy query operator has been removed, keying withing the query pipeline is now automatic (#144)

  • Updated dependencies [1fbb844, 338efc2, ee5d026, e7b036c, e4feb0c]:

    • @tanstack/db@0.0.5

0.0.4

Patch Changes

  • Updated dependencies [8ce449e]:
    • @tanstack/db@0.0.4

0.0.3

Patch Changes

  • Updated dependencies [b29420b]:
    • @tanstack/db@0.0.3

0.0.2

Patch Changes

  • Fixed an issue with injecting the optimistic state removal into the reactive live query. (#78)

  • Updated dependencies [4c82edb]:

    • @tanstack/db@0.0.2

0.0.3

Patch Changes

  • Make transactions first class & move ownership of mutationFn from collections to transactions (#53)

  • Updated dependencies [b42479c]:

    • @tanstack/db@0.0.3

0.0.2

Patch Changes

  • make mutationFn optional for read-only collections (#12)

  • Updated dependencies [9bb6e89, 8eb7e9b]:

    • @tanstack/db@0.0.2

0.0.1

Patch Changes

  • feat: Initial release (#2)

  • Updated dependencies [2d2dd77]:

    • @tanstack/db@0.0.1