-
Propagate initial query sync failures through dependent live queries and readiness promises, including recovery and late subscribers, while preserving a ready cached snapshot on later refetch failures. Let sync adapters pass the original failure to
markError(error)so readiness promises reject with that cause. Isolate adapter callbacks by sync session, preserve synchronous startup errors, and prevent rejected deduplicated subset requests from creating detached promise rejections. (#1751) -
Updated dependencies [
c521b5d]:- @tanstack/db@0.8.2
-
Rebuild correlated include materialization as one D2 graph, fixing stale or missing nested results across route changes, batching, lazy loading, optimistic updates, and layered queries. Add canonical structural relation keys, abortable subset demand, and coherent publication for Collection-valued includes. Dispose delayed PowerSync subset hooks after cleanup, and prevent released Query Collection cache results from reaching the collection. (#1740)
-
Updated dependencies [
5d9335d,a20352a]:- @tanstack/db@0.8.1
-
Add SSR through request-scoped
DbClientinstances, 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.
-
Updated dependencies [
4b9e8cd]:- @tanstack/db@0.8.0
- Updated dependencies [
5f63996]:- @tanstack/db@0.7.2
- Updated dependencies [
424382b]:- @tanstack/db@0.7.1
- Updated dependencies [
8ee783d]:- @tanstack/db@0.6.17
-
Add eager collection support for TanStack Query
initialDataandinitialDataUpdatedAt, including wrapped response projection and collection-local initialization on shared QueryClient instances. (#1683)QueryClient-default
placeholderDatano longer materializes as collection rows, and QueryClient-defaultinitialDatano longer seeds on-demand subset observers.
- Clean up empty query ownership state while preserving authoritative empty results and retained-row lifecycle behavior. (#1672)
- Add top-level Query Collection support for additional Query observer options while preserving QueryClient defaultOptions behavior. (#1665)
-
Fix temporary query readiness listeners so subset unload and collection cleanup release them correctly during in-flight requests. (#1673)
-
Extract internal query row ownership helpers to make lifecycle cleanup paths easier to reason about while preserving existing behavior. (#1664)
-
Updated dependencies [
8258d09,286964d]:- @tanstack/db@0.6.16
-
Clarify that
selectextracts rows for DB materialization while preserving the wrapped TanStack Query cache response. (#1654) -
Document the current TanStack Query option compatibility surface for Query Collections, including forwarded options, QueryClient defaults, adapter-owned fields, and common options that are not currently exposed. (#1653)
-
Add coverage for query invalidation behavior across eager and on-demand query collections. (#1655)
-
Updated dependencies [
eabcea7,6d4c096]:- @tanstack/db@0.6.15
- Keep on-demand load subset subscription state out of TanStack Query metadata so dehydrated query state remains safe to persist with structured-clone based persisters. (#1644)
- Updated dependencies [
397e12a]:- @tanstack/db@0.6.14
- Updated dependencies [
2b27dd1]:- @tanstack/db@0.6.12
- Updated dependencies [
307fdf8]:- @tanstack/db@0.6.10
- Forward
gcTimefromqueryCollectionOptionsto the underlying TanStack Query observer. ThegcTimeoption was previously documented in the config shape but silently dropped before reaching the observer, leaving consumers stuck on thequeryClientdefault. Closes #1546. (#1568)
- Updated dependencies [
3827b62]:- @tanstack/db@0.6.8
- Updated dependencies [
4e9ab39]:- @tanstack/db@0.6.6
- Updated dependencies [
1e69dd6]:- @tanstack/db@0.6.4
- Updated dependencies [
8b7fb1a]:- @tanstack/db@0.6.1
-
fix: prevent stale query refreshes from overwriting optimistic offline changes on reconnect (#1390)
When reconnecting with pending offline transactions, query-backed collections now defer processing query refreshes until queued writes finish replaying, avoiding temporary reverts to stale server data.
-
fix: default persisted query retention to gcTime when omitted (#1400)
When
persistedGcTimeis not provided, query collections now use the query's effectivegcTimeas the persisted retention TTL. This prevents unexpectedly early cleanup of persisted rows. -
fix: Prevent stale query cache from re-inserting deleted items when a destroyed observer is recreated with gcTime > 0. (#1387)
-
Updated dependencies [
f60384b,b8abc02,09c7afc,bb09eb1,179d666,43ecbfa,055fd94,055fd94,055fd94,055fd94,85f5435,b65d8f7,e0df07e,9952921,d351c67]:- @tanstack/db@0.6.0
- Updated dependencies [
c3e6a96]:- @tanstack/db@0.5.33
- Updated dependencies [
bf1d078]:- @tanstack/db@0.5.31
- Updated dependencies [
e9d0fd8]:- @tanstack/db@0.5.30
-
Improve
queryCollectionOptionstype compatibility with TanStack Query option objects. (#1289)- Accept
queryFnreturn types ofT | Promise<T>instead of requiringPromise<T>. - Align
enabled,staleTime,refetchInterval,retry, andretryDelaywithQueryObserverOptionstyping. - Support tagged
queryKeyvalues (DataTag) fromqueryOptions(...)spread usage. - Preserve runtime safety: query collections still require an executable
queryFn, and wrapped responses still requireselect.
- Accept
-
Updated dependencies [
77b815e,ac4ce67]:- @tanstack/db@0.5.29
- Updated dependencies [
46450e7]:- @tanstack/db@0.5.28
-
Make loadSubsetOptions optional in QueryCollectionMeta to fix query-core interface pollution (#1061) (#1238)
-
Updated dependencies [
85c373e,9184dcc,83d5ac8]:- @tanstack/db@0.5.26
-
Fix
isReadytracking for on-demand live queries without orderBy. Previously, non-ordered live queries usingsyncMode: 'on-demand'were incorrectly marked as ready before data finished loading. Also fixpreload()promises hanging when cleanup occurs before the collection becomes ready. Additionally, fix concurrent live queries subscribing to the same source collection - each now independently tracks loading state. (#1192) -
Updated dependencies [
43c7c9d,284ebcc]:- @tanstack/db@0.5.25
- Updated dependencies [
7099459]:- @tanstack/db@0.5.24
- Updated dependencies [
05130f2]:- @tanstack/db@0.5.23
-
Fix updating all active query caches on directWrite for on-demand collections.Previously directWrite operations (e.g. writeUpdate/writeInsert) only updated the cache at the base query key for on-demand collections, leading to stale data when components remounted. This change ensures all active query cache keys are updated so data persists correctly. (#1155)
-
Updated dependencies [
f9b741e]:- @tanstack/db@0.5.22
-
Fix syncedData not updating when manual write operations (writeUpsert, writeInsert, etc.) are called after async operations in mutation handlers. Previously, the sync transaction would be blocked by the persisting user transaction, leaving syncedData stale until the next sync cycle. (#1130)
-
Updated dependencies [
6745ed0,1b22e40,7a2cacd,bdf9405]:- @tanstack/db@0.5.21
- Fix refetch such that it returns the query observer results instead of undefined. (#1132)
- Updated dependencies []:
- @tanstack/db@0.5.20
- Updated dependencies [
c1247e8]:- @tanstack/db@0.5.18
-
Fix on-demand sync behavior so the full TanStack Query lifecycle is respected. (#1007)
This patch resolves an issue where using on-demand synchronization could break the query lifecycle, including the error reported in #998.
-
Updated dependencies [
f795a67,d542667,6503c09,b1cc4a7]:- @tanstack/db@0.5.17
- Updated dependencies [
41308b8]:- @tanstack/db@0.5.16
- Updated dependencies [
32ec4d8]:- @tanstack/db@0.5.15
- Updated dependencies [
26ed0aa]:- @tanstack/db@0.5.14
-
Fix writeInsert/writeUpsert throwing error when collection uses select option (#1023)
When a Query Collection was configured with a
selectoption to extract items from a wrapped API response (e.g.,{ data: [...], meta: {...} }), callingwriteInsert()orwriteUpsert()would corrupt the query cache and trigger the error: "select() must return an array of objects".The fix routes cache updates through a new
updateCacheDatafunction that preserves the wrapper structure by using theselectfunction to identify which property contains the items array (via reference equality), then updates only that property while keeping metadata intact.
-
Enhanced LoadSubsetOptions with separate cursor expressions and offset for flexible pagination. (#960)
⚠️ Breaking Change for Custom Sync Layers / Query Collections:LoadSubsetOptions.whereno longer includes cursor expressions for pagination. If you have a custom sync layer or query collection that implementsloadSubset, you must now handle pagination separately:- Cursor-based pagination: Use the new
cursorproperty (cursor.whereFromandcursor.whereCurrent) and combine them withwhereyourself - Offset-based pagination: Use the new
offsetproperty
Previously, cursor expressions were baked into the
whereclause. Now they are passed separately so sync layers can choose their preferred pagination strategy.Changes:
- Added
CursorExpressionstype withwhereFrom,whereCurrent, and optionallastKeyproperties - Added
cursortoLoadSubsetOptionsfor cursor-based pagination (separate fromwhere) - Added
offsettoLoadSubsetOptionsfor offset-based pagination support - Electric sync layer now makes two parallel
requestSnapshotcalls when cursor is present:- One for
whereCurrent(all ties at boundary, no limit) - One for
whereFrom(rows after cursor, with limit)
- One for
- Query collection serialization now includes
offsetfor query key generation - Added
truncateevent to collections, emitted when synced data is truncated (e.g., aftermust-refetch) - Fixed
setWindowpagination: cursor expressions are now correctly built when paging through results - Fixed offset tracking:
loadNextItemsnow passes the correct window offset to prevent incorrect deduplication CollectionSubscribernow listens fortruncateevents to reset cursor tracking state
Benefits:
- Sync layers can choose between cursor-based or offset-based pagination strategies
- Electric can efficiently handle tie-breaking with two targeted requests
- Better separation of concerns between filtering (
where) and pagination (cursor/offset) setWindowcorrectly triggers backend loading for subsequent pages in multi-column orderBy queries- Cursor state is properly reset after truncation, preventing stale cursor data from being used
- Cursor-based pagination: Use the new
-
Updated dependencies [
b3b1940,09da081,86ad40c]:- @tanstack/db@0.5.12
-
fix(query-db-collection): use deep equality for object field comparison in query observer (#967)
Fixed an issue where updating object fields (non-primitives) with
refetch: falseinonUpdatehandlers would cause the value to rollback to the previous state every other update. The query observer was using shallow equality (===) to compare items, which compares object properties by reference rather than by value. This caused the observer to incorrectly detect differences and write stale data back to syncedData. Now usesdeepEqualsfor proper value comparison. -
Use regular dependency for @tanstack/db instead of peerDependency to match the standard pattern used by other TanStack DB packages and prevent duplicate installations (#952)
-
Updated dependencies [
c4b9399,a1a484e]:- @tanstack/db@0.5.11
-
fix: ensure ctx.meta.loadSubsetOptions type-safety works automatically (#869)
The module augmentation for ctx.meta.loadSubsetOptions is now guaranteed to load automatically when importing from @tanstack/query-db-collection. Previously, users needed to explicitly import QueryCollectionMeta or use @ts-ignore to pass ctx.meta?.loadSubsetOptions to parseLoadSubsetOptions.
Additionally, QueryCollectionMeta is now an interface (instead of a type alias), enabling users to safely extend meta with custom properties via declaration merging:
declare module '@tanstack/query-db-collection' { interface QueryCollectionMeta { myCustomProperty: string } }
-
Updated dependencies [
c8a2c16]:- @tanstack/db@0.5.6
-
Fix data loss on component remount by implementing reference counting for QueryObserver lifecycle (#870)
What changed vs main:
Previously, when live query subscriptions unsubscribed, there was no tracking of which rows were still needed by other active queries. This caused data loss during remounts.
This PR adds reference counting infrastructure to properly manage QueryObserver lifecycle:
- Pass same predicates to
unloadSubsetthat were passed toloadSubset - Use them to compute the queryKey (via
generateQueryKeyFromOptions) - Use existing machinery (
queryToRowsmap) to find rows that query loaded - Decrement the ref count
- GC rows where count reaches 0 (no longer referenced by any active query)
Impact:
- Navigation back to previously loaded pages shows cached data immediately
- No unnecessary refetches during quick remounts (< gcTime)
- Multiple live queries with identical predicates correctly share QueryObservers
- Proper row-level cleanup when last subscriber leaves
- TanStack Query's cache lifecycle (gcTime) is fully respected
- No data leakage from in-flight requests when unsubscribing
- Pass same predicates to
-
Updated dependencies [
077fc1a]:- @tanstack/db@0.5.5
-
Improved the type of the queryFn's ctx.meta property of the Query Collection to include the loadSubsetOptions (#857)
-
Fixed bug where optimistic state leaked into syncedData when using writeInsert inside onInsert handlers. Previously, when syncing server-generated fields (like IDs or timestamps) using writeInsert within an onInsert handler, the QueryClient cache was updated with combined visible state (including optimistic changes), which triggered the query observer to write optimistic values back to syncedData. Now the cache is correctly updated with only server-confirmed state, ensuring syncedData maintains separation from optimistic state. (#879)
-
Updated dependencies [
acb3e4f,464805d,2c2e4db,15c772f]:- @tanstack/db@0.5.4
-
Automatically append predicates to static queryKey in on-demand mode. (#800)
When using a static
queryKeywithsyncMode: 'on-demand', the system now automatically appends serialized LoadSubsetOptions to create unique cache keys for different predicate combinations. This fixes an issue where all live queries with different predicates would share the same TanStack Query cache entry, causing data to be overwritten.Before:
// This would cause conflicts between different queries queryCollectionOptions({ queryKey: ['products'], // Static key syncMode: 'on-demand', queryFn: async (ctx) => { const { where, limit } = ctx.meta.loadSubsetOptions return fetch(`/api/products?...`).then((r) => r.json()) }, })
With different live queries filtering by
category='A'andcategory='B', both would share the same cache key['products'], causing the last query to overwrite the first.After: Static queryKeys now work correctly in on-demand mode! The system automatically creates unique cache keys:
- Query with
category='A'→['products', '{"where":{...A...}}'] - Query with
category='B'→['products', '{"where":{...B...}}']
Key behaviors:
- ✅ Static queryKeys now work correctly with on-demand mode (automatic serialization)
- ✅ Function-based queryKeys continue to work as before (no change)
- ✅ Eager mode with static queryKeys unchanged (no automatic serialization)
- ✅ Identical predicates correctly reuse the same cache entry
This makes the documentation example work correctly without requiring users to manually implement function-based queryKeys for predicate push-down.
- Query with
-
Updated dependencies [
846a830,8e26dcf]:- @tanstack/db@0.5.3
-
Temporarily remove
loadSubsetcall deduplication in query collection. We need to revisit our approach to deduplication to ensure correctness. See #836 for discussion on the proper implementation strategy. (#840) -
Updated dependencies [
a83a818]:- @tanstack/db@0.5.1
-
Add expression helper utilities for parsing LoadSubsetOptions in queryFn. (#763)
When using
syncMode: 'on-demand', TanStack DB now provides helper functions to easily parse where clauses, orderBy, and limit predicates into your API's format:parseWhereExpression: Parse where clauses with custom handlers for each operatorparseOrderByExpression: Parse order by into simple array formatextractSimpleComparisons: Extract simple AND-ed filtersparseLoadSubsetOptions: Convenience function to parse all options at oncewalkExpression,extractFieldPath,extractValue: Lower-level helpers
Example:
import { parseLoadSubsetOptions } from '@tanstack/db' // or from "@tanstack/query-db-collection" (re-exported for convenience) queryFn: async (ctx) => { const { where, orderBy, limit } = ctx.meta.loadSubsetOptions const parsed = parseLoadSubsetOptions({ where, orderBy, limit }) // Build API request from parsed filters const params = new URLSearchParams() parsed.filters.forEach(({ field, operator, value }) => { if (operator === 'eq') { params.set(field.join('.'), String(value)) } }) return fetch(`/api/products?${params}`).then((r) => r.json()) }
This eliminates the need to manually traverse expression AST trees when implementing predicate push-down.
-
Handle pushed-down predicates (#763)
-
Updated dependencies [
243a35a,f9d11fc,7aedf12,28f81b5,28f81b5,f6ac7ea,01093a7]:- @tanstack/db@0.5.0
-
Add QueryObserver state utilities and convert error utils to getters (#742)
Exposes TanStack Query's QueryObserver state through QueryCollectionUtils, providing visibility into sync status beyond just error states. Also converts existing error state utilities from methods to getters for consistency with TanStack DB/Query patterns.
Breaking Changes:
lastError(),isError(), anderrorCount()are now getters instead of methods- Before:
collection.utils.lastError() - After:
collection.utils.lastError
- Before:
New Utilities:
isFetching- Check if query is currently fetching (initial or background)isRefetching- Check if query is refetching in backgroundisLoading- Check if query is loading for first timedataUpdatedAt- Get timestamp of last successful data updatefetchStatus- Get current fetch status ('fetching' | 'paused' | 'idle')
Use Cases:
- Show loading indicators during background refetches
- Implement "Last updated X minutes ago" UI patterns
- Better understanding of query sync behavior
Example Usage:
const collection = queryCollectionOptions({ // ... config }) // Check sync status if (collection.utils.isFetching) { console.log('Syncing with server...') } if (collection.utils.isRefetching) { console.log('Background refresh in progress') } // Show last update time const lastUpdate = new Date(collection.utils.dataUpdatedAt) console.log(`Last synced: ${lastUpdate.toLocaleTimeString()}`) // Check error state (now using getters) if (collection.utils.isError) { console.error('Sync failed:', collection.utils.lastError) console.log(`Failed ${collection.utils.errorCount} times`) }
-
Fix dependency bundling issues by moving @tanstack/db to peerDependencies (#766)
What Changed:
Moved
@tanstack/dbfrom regular dependencies to peerDependencies in:@tanstack/offline-transactions@tanstack/query-db-collection
Removed
@opentelemetry/apidependency from@tanstack/offline-transactions.Why:
These extension packages incorrectly declared
@tanstack/dbas both a regular dependency AND a peerDependency simultaneously. This caused lock files to develop conflicting versions, resulting in multiple instances of@tanstack/dbbeing installed in consuming applications.The fix removes
@tanstack/dbfrom regular dependencies and keeps it only as a peerDependency. This ensures only one version of@tanstack/dbis installed in the dependency tree, preventing version conflicts.For local development,
@tanstack/dbremains in devDependencies so the packages can be built and tested independently. -
Updated dependencies [
6c55e16,7805afb,1367756]:- @tanstack/db@0.4.20
- Updated dependencies [
75470a8]:- @tanstack/db@0.4.19
- Updated dependencies [
49bcaa5]:- @tanstack/db@0.4.17
- Updated dependencies [
6738247]:- @tanstack/db@0.4.15
-
Behavior change:
utils.refetch()now uses exact query key targeting (previously used prefix matching). This prevents unintended cascading refetches of related queries. For example, refetching['todos', 'project-1']will no longer trigger refetches of['todos']or['todos', 'project-2']. (#552)Additionally,
utils.refetch()now bypassesenabled: falseto support manual/imperative refetch patterns (matching TanStack Query hook behavior) and returnsQueryObserverResultinstead ofvoidfor better DX.
- Updated dependencies [
970616b]:- @tanstack/db@0.4.14
- Updated dependencies [
3c9526c]:- @tanstack/db@0.4.13
-
Fix queryCollectionOptions to respect QueryClient defaultOptions when not overridden (#707)
Previously, when creating a QueryClient with defaultOptions (e.g., staleTime, retry, refetchOnWindowFocus), these options were ignored by queryCollectionOptions unless explicitly specified again in the collection config. This required duplicating configuration and prevented users from setting global defaults.
Now, queryCollectionOptions properly respects the QueryClient's defaultOptions as fallbacks. Options explicitly provided in queryCollectionOptions will still override the defaults.
Example - this now works as expected:
const dbQueryClient = new QueryClient({ defaultOptions: { queries: { refetchOnWindowFocus: false, staleTime: Infinity, }, }, }) queryCollectionOptions({ id: 'wallet-accounts', queryKey: ['wallet-accounts'], queryClient: dbQueryClient, // staleTime: Infinity is now inherited from defaultOptions })
-
Fix writeDelete/writeUpdate validation to check synced store only (#708)
Fixed issue where calling
writeDelete()orwriteUpdate()inside mutation handlers (likeonDelete) would throw errors when optimistic updates were active. These write operations now correctly validate against the synced store only, not the combined view (synced + optimistic).This allows patterns like calling
writeDelete()inside anonDeletehandler to work correctly, enabling users to write directly to the synced store while the mutation is being persisted to the backend.Fixes #706
- Updated dependencies [
5566b26]:- @tanstack/db@0.4.11
- Updated dependencies [
6692aad]:- @tanstack/db@0.4.7
- Updated dependencies [
7556fb6]:- @tanstack/db@0.4.5
-
Fix collection.preload() hanging when called without startSync or subscribers. The QueryObserver now subscribes immediately when sync starts (from preload(), startSync, or first subscriber), while maintaining the staleTime behavior by dynamically unsubscribing when subscriber count drops to zero. (#635)
-
Updated dependencies [
56b870b,f623990,5f43d5f,05776f5,d27d32a]:- @tanstack/db@0.4.4
- Updated dependencies [
32f2212]:- @tanstack/db@0.4.3
-
Fix
staleTimebehavior by automatically subscribing/unsubscribing from TanStack Query based on collection subscriber count. (#462)Previously, query collections kept a QueryObserver permanently subscribed, which broke TanStack Query's
staleTimeand window-focus refetch behavior. Now the QueryObserver properly goes inactive when the collection has no subscribers, restoring normalstaleTime/gcTimesemantics. -
query-collection now supports a
selectfunction to transform raw query results into an array of items. This is useful for APIs that return data with metadata or nested structures, ensuring metadata remains cached while collections work with the unwrapped array. (#551) -
Updated dependencies [
51c6bc5,248e2c6,ce7e2b2,1b832ff]:- @tanstack/db@0.4.2
- Updated dependencies [
8cd0876]:- @tanstack/db@0.4.1
-
Refactor the main Collection class into smaller classes to make it easier to maintain. (#560)
-
Updated dependencies [
2f87216,ac6250a,2f87216]:- @tanstack/db@0.4.0
- Updated dependencies [
cacfca2]:- @tanstack/db@0.3.2
- Updated dependencies [
5f51f35]:- @tanstack/db@0.3.1
-
Refactor of the types of collection config factories for better type inference. (#530)
-
Define BaseCollectionConfig interface and let all collections extend it. (#531)
-
Updated dependencies [
b03894d,3968087]:- @tanstack/db@0.2.5
-
Add error tracking and retry methods to query collection utils. (#441)
-
Updated dependencies [
92febbf,b487430]:- @tanstack/db@0.2.4
- Updated dependencies [
b162556]:- @tanstack/db@0.2.3
- Updated dependencies [
33515c6]:- @tanstack/db@0.2.2
- Updated dependencies [
620ebea]:- @tanstack/db@0.2.1
-
fix: race condition creating a collection from a query that has already loaded (#495)
-
Updated dependencies [
cc4c34a]:- @tanstack/db@0.1.12
- Updated dependencies [
b869f68]:- @tanstack/db@0.1.11
- Updated dependencies [
d64b4a8]:- @tanstack/db@0.1.9
- Updated dependencies [
ad33e9e]:- @tanstack/db@0.1.6
-
Add type inference of the collection type from the query collection config
queryFnreturn type (#403) -
Updated dependencies [
9a5a20c]:- @tanstack/db@0.1.5
- Updated dependencies [
0cb7699]:- @tanstack/db@0.1.3
-
Ensure that you can use optional properties in the
selectandjoinclauses of a query, and fix an issue where standard schemas were not properly carried through to live queries. (#377) -
Updated dependencies [
bb5d50e,97b595e]:- @tanstack/db@0.1.2
- Improve writeBatch API to use callback pattern (#378)
- Changed
writeBatchfrom accepting an array of operations to accepting a callback function - Write operations called within the callback are automatically batched together
- This provides a more intuitive API similar to database transactions
- Added comprehensive documentation for Query Collections including direct writes feature
- Changed
-
Add meta support to QueryCollectionConfig to allow passing additional context to queryFn. (#363)
-
Updated dependencies [
bc2f204,bda3f24]:- @tanstack/db@0.1.1
- Move @tanstack/query-core from dependencies to peerDependencies to avoid version conflicts when users already have react-query or query-core installed. This is a non-breaking change as the package will continue to work with any 5.x version of query-core. (#351)
- Add manual write methods to QueryCollectionUtils interface to enable direct state updates from external sources. Introduces writeInsert, writeUpdate, writeDelete, writeUpsert, and writeBatch methods that bypass the normal optimistic update flow for WebSocket/real-time scenarios. All methods include proper transaction handling, data validation, and automatic query cache synchronization. (#303)
- 0.1 release - first beta 🎉 (#332)
- Updated dependencies [
6e8d7f6]:- @tanstack/db@0.0.33
-
Fix LiveQueryCollection hanging when source collections have no data (#309)
Fixed an issue where
LiveQueryCollection.preload()would hang indefinitely when source collections callmarkReady()without data changes (e.g., when queryFn returns empty array).The fix implements a proper event-based solution:
- Collections now emit empty change events when becoming ready with no data
- WHERE clause filtered subscriptions now correctly pass through empty ready signals
- Both regular and WHERE clause optimized LiveQueryCollections now work correctly with empty source collections
-
Updated dependencies [
e04bd12]:- @tanstack/db@0.0.32
- Updated dependencies [
3e9a36d]:- @tanstack/db@0.0.31
- Updated dependencies [
6bdde55]:- @tanstack/db@0.0.30
-
feat: Replace string-based errors with named error classes for better error handling (#297)
This comprehensive update replaces all string-based error throws throughout the TanStack DB codebase with named error classes, providing better type safety and developer experience.
- Root
TanStackDBErrorclass - all errors inherit from a common base for unified error handling - Named error classes organized by package and functional area
- Type-safe error handling using
instanceofchecks instead of string matching - Package-specific error definitions - each adapter has its own error classes
- Better IDE support with autocomplete for error types
Contains generic errors used across the ecosystem:
- Collection configuration, state, and operation errors
- Transaction lifecycle and mutation errors
- Query building, compilation, and execution errors
- Storage and serialization errors
Each adapter now exports its own specific error classes:
@tanstack/electric-db-collection: Electric-specific errors@tanstack/trailbase-db-collection: TrailBase-specific errors@tanstack/query-db-collection: Query collection specific errors
- Error handling code using string matching will need to be updated to use
instanceofchecks - Some error messages may have slight formatting changes
- Adapter-specific errors now need to be imported from their respective packages
Before:
try { collection.insert(data) } catch (error) { if (error.message.includes('already exists')) { // Handle duplicate key error } }
After:
import { DuplicateKeyError } from '@tanstack/db' try { collection.insert(data) } catch (error) { if (error instanceof DuplicateKeyError) { // Type-safe error handling } }
Before:
// Electric collection errors were imported from @tanstack/db import { ElectricInsertHandlerMustReturnTxIdError } from '@tanstack/db'
After:
// Now import from the specific adapter package import { ElectricInsertHandlerMustReturnTxIdError } from '@tanstack/electric-db-collection'
New:
import { TanStackDBError } from '@tanstack/db' try { // Any TanStack DB operation } catch (error) { if (error instanceof TanStackDBError) { // Handle all TanStack DB errors uniformly console.log('TanStack DB error:', error.message) } }
- Type Safety: All errors now have specific types that can be caught with
instanceof - Unified Error Handling: Root
TanStackDBErrorclass allows catching all library errors with a single check - Better Package Separation: Each adapter manages its own error types
- Developer Experience: Better IDE support with autocomplete for error types
- Maintainability: Error definitions are co-located with their usage
- Consistency: Uniform error handling patterns across the entire codebase
All error classes maintain the same error messages and behavior while providing better structure and package separation.
- Root
-
Updated dependencies [
ced0657,dcfef51,360b0df,608be0c,5260ee3]:- @tanstack/db@0.0.29
- Updated dependencies [
bec8620]:- @tanstack/db@0.0.27
-
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
-
Add explicit collection readiness detection with
isReady()andmarkReady()(#270)- Add
isReady()method to check if a collection is ready for use - Add
onFirstReady()method to register callbacks for when collection becomes ready - Add
markReady()to SyncConfig interface for sync implementations to explicitly signal readiness - Replace
onFirstCommit()withonFirstReady()for better semantics - Update status state machine to allow
loading→readytransition for cases with no data to commit - Update all sync implementations (Electric, Query, Local-only, Local-storage) to use
markReady() - Improve error handling by allowing collections to be marked ready even when sync errors occur
This provides a more intuitive and ergonomic API for determining collection readiness, replacing the previous approach of using commits as a readiness signal.
- Add
-
Updated dependencies [
1758eda,20f810e]:- @tanstack/db@0.0.25
- Updated dependencies [
056609e]:- @tanstack/db@0.0.23
- Updated dependencies [
aeee9a1]:- @tanstack/db@0.0.22
-
Move Collections to their own packages (#252)
- Move local-only and local-storage collections to main
@tanstack/dbpackage - Create new
@tanstack/electric-db-collectionpackage for ElectricSQL integration - Create new
@tanstack/query-db-collectionpackage for TanStack Query integration - Delete
@tanstack/db-collectionspackage (removed from repo) - Update example app and documentation to use new package structure
Why?
- Better separation of concerns
- Independent versioning for each collection type
- Cleaner dependencies (electric collections don't need query deps, etc.)
- Easier to add more collection types moving forward
- Move local-only and local-storage collections to main
-
Updated dependencies [
8e23322]:- @tanstack/db@0.0.21