Open History to see the last commit
1---
2title: Query Collection
3---
4
5Query collections provide seamless integration between TanStack DB and TanStack Query, enabling automatic synchronization between your local database and remote data sources.
6
7## Overview
8
9The `@tanstack/query-db-collection` package allows you to create collections that:
10
11- Automatically fetch remote data via TanStack Query
12- Support optimistic updates with automatic rollback on errors
13- Handle persistence through customizable mutation handlers
14- Provide direct write capabilities for directly writing to the sync store
15
16## Installation
17
18```bash
19npm install @tanstack/query-db-collection @tanstack/query-core @tanstack/db
20```
21
22## Basic Usage
23
24```typescript
25import { QueryClient } from "@tanstack/query-core"
26import { DbClient, collectionOptions } from "@tanstack/db"
27import { queryCollectionOptions } from "@tanstack/query-db-collection"
28
29const queryClient = new QueryClient()
30const db = new DbClient({ queryClient })
31
32const todosCollection = collectionOptions("todos", (client) =>
33 queryCollectionOptions({
34 id: "todos",
35 queryKey: ["todos"],
36 queryFn: async () => {
37 const response = await fetch("/api/todos")
38 return response.json()
39 },
40 queryClient: client.requireDependency<QueryClient>("queryClient"),
41 getKey: (item) => item.id,
42 })
43)
44
45const todos = db.collection(todosCollection)
46```
47
48## Configuration Options
49
50The `queryCollectionOptions` function accepts the following options:
51
52### Required Options
53
54- `queryKey`: The query key for TanStack Query. Can be a static array or a function that receives `LoadSubsetOptions` and returns a key. When using a function, all returned keys must share the base key (`queryKey({})`) as a prefix — see [Query Key Prefix Convention](#query-key-prefix-convention).
55- `queryFn`: Function that fetches data from the server
56- `queryClient`: TanStack Query client instance
57- `getKey`: Function to extract the unique key from an item
58
59### Request-scoped QueryClient
60
61`queryCollectionOptions` needs a `queryClient`. In SSR, TanStack Start, tests,
62or multi-tenant apps, that client is request-local rather than module-global.
63Put it on `DbClient`, then resolve it inside the collection descriptor factory:
64
65```typescript
66import { QueryClient } from "@tanstack/query-core"
67import { DbClient, collectionOptions } from "@tanstack/db"
68import { queryCollectionOptions } from "@tanstack/query-db-collection"
69
70interface Todo {
71 id: string
72 title: string
73}
74
75export const todoCollection = collectionOptions("todos", (client) =>
76 queryCollectionOptions<Todo>({
77 id: "todos",
78 queryKey: ["todos"],
79 queryFn: async () => {
80 const response = await fetch("/api/todos")
81 return response.json() as Promise<Array<Todo>>
82 },
83 queryClient: client.requireDependency<QueryClient>("queryClient"),
84 getKey: (todo) => todo.id,
85 })
86)
87
88export function createRequestClients() {
89 const queryClient = new QueryClient()
90 const dbClient = new DbClient({ queryClient })
91 return { queryClient, dbClient }
92}
93```
94
95`dbClient.collection(todoCollection)` memoizes one collection instance for that
96descriptor and client. A second `DbClient` materializes fresh adapter state and
97uses its own `QueryClient`.
98
99Passing `queryClient` directly to `queryCollectionOptions` remains supported for
100`createCollection(...)` and existing apps. When a descriptor is materialized,
101an explicit `DbClient` dependency takes precedence; the configured
102`queryClient` is the backwards-compatible fallback.
103
104### Business-Scoped Collection Factories
105
106A tenant, project, account, or route parameter can define a **business scope**:
107the server resource that a collection represents. Include the scope in the
108descriptor id, Query key, and `queryFn`. This extends the
109[request-scoped QueryClient pattern](#request-scoped-queryclient) with an
110explicit scope parameter:
111
112```typescript
113interface Todo {
114 id: string
115 title: string
116 projectId: string
117}
118
119async function fetchProjectTodos(projectId: string): Promise<Array<Todo>> {
120 const response = await fetch(`/api/projects/${projectId}/todos`)
121 return response.json()
122}
123
124function createProjectTodosDescriptor(
125 projectId: string,
126) {
127 return collectionOptions(`project:${projectId}:todos`, (client) =>
128 queryCollectionOptions<Todo>({
129 id: `project:${projectId}:todos`,
130 queryKey: ["projects", projectId, "todos"],
131 queryFn: () => fetchProjectTodos(projectId),
132 queryClient: client.requireDependency<QueryClient>("queryClient"),
133 getKey: (todo) => todo.id,
134 })
135 )
136}
137```
138
139The scope is part of the descriptor identity. `DbClient` resolves separately
140created descriptors with the same id to the same collection, so a React hook
141can create the descriptor from its current parameters:
142
143```typescript
144export function useProjectTodos(projectId: string) {
145 return useDbClient().collection(createProjectTodosDescriptor(projectId))
146}
147```
148
149Only the first descriptor for an id is materialized. Include every scope value
150that changes the collection in both its descriptor id and Query key. Call
151`await dbClient.cleanup()` when the client scope ends.
152
153A business scope is separate from a **relational subset** requested by a live query. With `syncMode: "on-demand"`, `LoadSubsetOptions` describes predicates, ordering, limits, and offsets within one business-scoped collection. These options reach `queryFn` through `ctx.meta.loadSubsetOptions` and determine the subset Query keys. See [QueryFn and Predicate Push-Down](#queryfn-and-predicate-push-down).
154
155Do not create a collection for each `where`, `orderBy`, or `limit`. Reuse the business-scoped collection and let on-demand loading represent those subsets. Create separate collections only for distinct server resources.
156
157### Query Options
158
159Query Collections use TanStack Query internally and expose supported Query observer options as top-level `queryCollectionOptions` fields.
160
161The following top-level Query Collection options are forwarded to the underlying Query observer:
162
163- `select`: Function that extracts the row array TanStack DB materializes from a wrapped Query response
164- `enabled`: Whether the query should automatically run (default: `true`)
165- `refetchInterval`: Refetch interval in milliseconds
166- `retry`: Retry configuration for failed queries
167- `retryDelay`: Delay between retries
168- `staleTime`: How long data is considered fresh
169- `gcTime`: How long unused query data stays in the Query cache
170- `refetchOnWindowFocus`: Whether to refetch when the window regains focus
171- `refetchOnReconnect`: Whether to refetch when the network reconnects
172- `refetchOnMount`: Whether to refetch when the observer mounts
173- `networkMode`: Query network mode
174- `initialData`: Initial Query response for eager collections
175- `initialDataUpdatedAt`: Timestamp used by TanStack Query to determine initial data freshness
176- `meta`: Metadata passed to the query function context. Query Collections may add `loadSubsetOptions` for on-demand queries.
177
178```ts
179const todosCollection = createCollection(
180 queryCollectionOptions({
181 queryKey: ["todos"],
182 queryFn: fetchTodos,
183 queryClient,
184 getKey: (todo) => todo.id,
185 refetchOnWindowFocus: true,
186 refetchOnReconnect: true,
187 refetchOnMount: "always",
188 networkMode: "online",
189 })
190)
191```
192
193Top-level `meta` is always merged by Query Collection so it can add on-demand `loadSubsetOptions`. Other supported top-level Query options are only passed to TanStack Query when you define them. If you omit them, `QueryClient.defaultOptions` can still apply.
194
195Some fields are owned or reinterpreted by the collection adapter rather than treated as ordinary Query option pass-through:
196
197- `queryKey`: Identifies the Query cache entry and, in on-demand mode, may be built from load-subset options.
198- `queryFn`: Fetches the complete collection state or the requested on-demand subset.
199- `select`: Extracts array rows from wrapped responses before they are stored in the collection. This is not the same contract as TanStack Query's `select` option.
200- `queryClient`: Supplies the Query client instance used by the collection.
201- `syncMode`: Controls whether the collection syncs eagerly or on demand.
202- `getKey`: Extracts each row's stable TanStack DB key.
203- Mutation handlers such as `onInsert`, `onUpdate`, and `onDelete`.
204
205Some TanStack Query fields are owned or reinterpreted by Query Collection and are intentionally not exposed as ordinary Query observer options:
206
207- `queryKey`, `queryFn`, and `queryClient`
208- `select` (Query Collection uses this for row extraction, not TanStack Query's observer-level `select` contract)
209- `meta` (merged by Query Collection so on-demand `loadSubsetOptions` can be included)
210- `subscribed` (Query Collection owns the observer subscription lifecycle)
211- `structuralSharing` and `notifyOnChangeProps` (managed by Query Collection synchronization)
212
213`placeholderData` is intentionally unsupported. TanStack Query treats placeholder data as observer-local presentation state rather than cached Query data. Materializing it would expose temporary UI data as collection-wide normalized rows. Render placeholders in the consuming UI instead.
214
215### Request Cancellation with `QueryFunctionContext.signal`
216
217TanStack Query passes an `AbortSignal` to `queryFn` through the query function
218context. Forward `ctx.signal` to `fetch` or another abortable client to make the
219request cancellable:
220
221```typescript
222const todosCollection = createCollection(
223 queryCollectionOptions({
224 queryKey: ["todos"],
225 queryFn: async (ctx) => {
226 const response = await fetch("/api/todos", {
227 signal: ctx.signal,
228 })
229
230 if (!response.ok) {
231 throw new Error("Failed to fetch todos")
232 }
233
234 return response.json() as Promise<Array<Todo>>
235 },
236 queryClient,
237 getKey: (todo) => todo.id,
238 }),
239)
240```
241
242Explicit collection cleanup cancels each exact Query key the collection is
243currently tracking before removing it from the Query cache:
244
245```typescript
246await todosCollection.cleanup()
247```
248
249The underlying request is aborted only when its client consumes `ctx.signal`.
250A client that ignores the signal may continue its request even though the
251collection has been cleaned up.
252
253An unloaded on-demand subset is no longer tracked. A later explicit collection
254cleanup does not revisit its Query key.
255
256Query cache entries are shared within a `QueryClient`. Explicit cleanup can
257affect other consumers using the same exact Query keys.
258
259On-demand subset unloading does not explicitly call
260`queryClient.cancelQueries()`. It removes the subset's Query observer. If this
261was the final observer and the query function consumed `ctx.signal`, TanStack
262Query aborts the request. If the signal was ignored, or another observer still
263uses the same exact Query key, the request may finish and remain cached until
264`gcTime`.
265
266### Using with `queryOptions(...)`
267
268If your app already uses TanStack Query's `queryOptions` helper (e.g. from `@tanstack/react-query`), you can spread compatible top-level options into `queryCollectionOptions`. Note that `queryFn` must be explicitly provided since query collections require it both in types and at runtime, and Query Collection's `select` option is for row extraction rather than TanStack Query observer-level selection:
269
270```typescript
271import { QueryClient } from "@tanstack/query-core"
272import { DbClient, collectionOptions } from "@tanstack/db"
273import { queryCollectionOptions } from "@tanstack/query-db-collection"
274import { queryOptions } from "@tanstack/react-query"
275
276const queryClient = new QueryClient()
277const db = new DbClient({ queryClient })
278
279const listOptions = queryOptions({
280 queryKey: ["todos"],
281 queryFn: async () => {
282 const response = await fetch("/api/todos")
283 return response.json() as Promise<Array<{ id: string; title: string }>>
284 },
285})
286
287const todosCollection = collectionOptions("todos", (client) =>
288 queryCollectionOptions({
289 id: "todos",
290 ...listOptions,
291 queryFn: (context) => listOptions.queryFn!(context),
292 queryClient: client.requireDependency<QueryClient>("queryClient"),
293 getKey: (item) => item.id,
294 }),
295)
296
297const todos = db.collection(todosCollection)
298```
299
300If `queryFn` is missing at runtime, `queryCollectionOptions` throws `QueryFnRequiredError`.
301
302### Initial Data
303
304Eager Query Collections support TanStack Query's `initialData` and
305`initialDataUpdatedAt` options. Initial data has the original Query response
306shape, is stored in the Query cache, and is immediately materialized as
307normalized collection rows. TanStack Query uses `initialDataUpdatedAt` together
308with `staleTime` to decide whether to fetch.
309
310```typescript
311const serverRenderedAt = Date.now()
312const initialTodos = [
313 { id: "1", title: "Write documentation" },
314 { id: "2", title: "Ship initial data support" },
315]
316
317const todosCollection = createCollection(
318 queryCollectionOptions({
319 queryKey: ["todos"],
320 queryFn: fetchTodos,
321 queryClient,
322 getKey: (todo) => todo.id,
323 initialData: initialTodos,
324 initialDataUpdatedAt: serverRenderedAt,
325 staleTime: 60_000,
326 }),
327)
328```
329
330An existing cached or hydrated Query response takes precedence over
331`initialData`. Query keys remain the cache identity: two collections using the
332same QueryClient and exact Query key observe one shared Query document, and a
333later collection's initializer does not replace it. Use distinct Query keys for
334independent documents.
335
336Initial data is supported only for eager collections. A collection-wide value
337cannot establish row membership for arbitrary on-demand predicates, ordering,
338limits, and offsets. For `syncMode: "on-demand"`, seed or hydrate the exact
339derived Query cache entries instead.
340
341If a stale initial response triggers a fetch, the initial rows remain available
342while it is in flight. A successful response reconciles them through the normal
343row ownership pipeline; an error retains the initial rows. Direct writes patch
344the eager Query cache in place. On-demand direct writes revalidate scoped
345entries as described below.
346
347### Selecting Rows from Wrapped Responses
348
349Many APIs return rows inside a response envelope that also contains metadata such as pagination cursors, totals, or request information. Use `select` to extract the row array that TanStack DB should materialize:
350
351```typescript
352interface TodosResponse {
353 items: Array<{ id: string; title: string }>
354 nextCursor?: string
355 total: number
356}
357
358const todosCollection = createCollection(
359 queryCollectionOptions({
360 queryKey: ["todos"],
361 queryFn: async (): Promise<TodosResponse> => {
362 const response = await fetch("/api/todos")
363 return response.json()
364 },
365 initialData: {
366 items: [{ id: "1", title: "Initial todo" }],
367 nextCursor: undefined,
368 total: 1,
369 },
370 select: (response) => response.items,
371 queryClient,
372 getKey: (item) => item.id,
373 }),
374)
375```
376
377`select` is a query-db-collection row extraction hook. It tells TanStack DB which rows to materialize while the TanStack Query cache keeps the original query response shape. In the example above, `queryClient.getQueryData(["todos"])` still returns the full `TodosResponse`, including `nextCursor` and `total`.
378
379The same projection applies to `initialData`: provide the complete response
380envelope, and Query Collection materializes the rows returned by `select` while
381preserving the envelope in the Query cache.
382
383This differs from TanStack Query's observer-level `select`: query-db-collection uses this option to bridge Query's response object into DB's normalized row store.
384
385In eager mode, direct write utilities such as `writeInsert`, `writeUpdate`, and `writeDelete` make a best-effort attempt to update the matching row array inside wrapped Query cache entries while preserving wrapper metadata. In on-demand mode, they revalidate active scoped queries and remove inactive or disabled cache entries instead of patching them with the full collection snapshot.
386
387This works automatically for simple wrappers such as:
388
389- `{ data: [...] }`
390- `{ items: [...] }`
391- `{ results: [...] }`
392
393Derived projections, such as `select: (response) => response.edges.map((edge) => edge.node)`, are read-side row extraction only. query-db-collection cannot generally reconstruct the original response envelope from updated rows. Refetch or invalidate the query if the wrapped cache must exactly reflect direct writes for a derived projection.
394
395### Collection Options
396
397- `id`: Unique identifier for the collection
398- `schema`: Schema for validating items
399- `sync`: Custom sync configuration
400- `startSync`: Whether to start syncing immediately (default: `true`)
401
402### Persistence Handlers
403
404- `onInsert`: Handler called before insert operations
405- `onUpdate`: Handler called before update operations
406- `onDelete`: Handler called before delete operations
407
408## Extending Meta with Custom Properties
409
410The `meta` option allows you to pass additional metadata to your query function. By default, Query Collections automatically include `loadSubsetOptions` in the meta object, which contains filtering, sorting, and pagination options for on-demand queries.
411
412Treat `ctx.meta.loadSubsetOptions` and its nested request data as read-only.
413Do not edit expression nodes, ordering options, Dates, byte arrays, or membership
414arrays. Build separate API parameters instead. Core retains request data without
415cloning it; changing submitted data can make the request disagree with its cache
416key. To change a query constant, supply a new value rather than mutating the old
417one. Cancellation through the request's `AbortSignal` remains supported.
418
419### Type-Safe Meta Access
420
421The `ctx.meta.loadSubsetOptions` property is automatically typed as `LoadSubsetOptions` without requiring any additional imports or type assertions:
422
423```typescript
424import { parseLoadSubsetOptions } from "@tanstack/query-db-collection"
425
426const collection = createCollection(
427 queryCollectionOptions({
428 queryKey: ["products"],
429 syncMode: "on-demand",
430 queryFn: async (ctx) => {
431 // ✅ Type-safe access - no @ts-ignore needed!
432 const options = parseLoadSubsetOptions(ctx.meta?.loadSubsetOptions)
433
434 // Use the parsed options to fetch only what you need
435 return api.getProducts(options)
436 },
437 queryClient,
438 getKey: (item) => item.id,
439 })
440)
441```
442
443### Adding Custom Meta Properties
444
445You can extend the meta type to include your own custom properties using TypeScript's module augmentation:
446
447```typescript
448// In a global type definition file (e.g., types.d.ts or global.d.ts)
449declare module "@tanstack/query-db-collection" {
450 interface QueryCollectionMeta {
451 // Add your custom properties here
452 userId?: string
453 includeDeleted?: boolean
454 cacheTTL?: number
455 }
456}
457```
458
459Once you've extended the interface, your custom properties are fully typed throughout your application:
460
461```typescript
462const collection = createCollection(
463 queryCollectionOptions({
464 queryKey: ["todos"],
465 queryFn: async (ctx) => {
466 // ✅ Both loadSubsetOptions and custom properties are typed
467 const { loadSubsetOptions, userId, includeDeleted } = ctx.meta
468
469 return api.getTodos({
470 ...parseLoadSubsetOptions(loadSubsetOptions),
471 userId,
472 includeDeleted,
473 })
474 },
475 queryClient,
476 getKey: (item) => item.id,
477 // Pass custom meta alongside Query Collection defaults
478 meta: {
479 userId: "user-123",
480 includeDeleted: false,
481 },
482 })
483)
484```
485
486### Important Notes
487
488- The module augmentation pattern follows TanStack Query's official approach for typing meta
489- `QueryCollectionMeta` is an interface (not a type alias), enabling proper TypeScript declaration merging
490- Your custom properties are merged with the base `loadSubsetOptions` property
491- All meta properties must be compatible with `Record<string, unknown>`
492- The augmentation should be done in a file that's included in your TypeScript compilation
493
494### Example: API Request Context
495
496A common use case is passing request context to your query function:
497
498```typescript
499// types.d.ts
500declare module "@tanstack/query-db-collection" {
501 interface QueryCollectionMeta {
502 authToken?: string
503 locale?: string
504 version?: string
505 }
506}
507
508// collections.ts
509const productsCollection = createCollection(
510 queryCollectionOptions({
511 queryKey: ["products"],
512 queryFn: async (ctx) => {
513 const { loadSubsetOptions, authToken, locale, version } = ctx.meta
514
515 return api.getProducts({
516 ...parseLoadSubsetOptions(loadSubsetOptions),
517 headers: {
518 Authorization: `Bearer ${authToken}`,
519 "Accept-Language": locale,
520 "API-Version": version,
521 },
522 })
523 },
524 queryClient,
525 getKey: (item) => item.id,
526 meta: {
527 authToken: session.token,
528 locale: "en-US",
529 version: "v1",
530 },
531 })
532)
533```
534
535## Persistence Handlers
536
537You can define handlers that are called when mutations occur. These handlers persist changes to your backend:
538
539```typescript
540const todosCollection = createCollection(
541 queryCollectionOptions({
542 queryKey: ["todos"],
543 queryFn: fetchTodos,
544 queryClient,
545 getKey: (item) => item.id,
546
547 onInsert: async ({ transaction }) => {
548 const newItems = transaction.mutations.map((m) => m.modified)
549 await api.createTodos(newItems)
550 // Auto-refetch happens after handler completes (pre-1.0 behavior)
551 },
552
553 onUpdate: async ({ transaction }) => {
554 const updates = transaction.mutations.map((m) => ({
555 id: m.key,
556 changes: m.changes,
557 }))
558 await api.updateTodos(updates)
559 },
560
561 onDelete: async ({ transaction }) => {
562 const ids = transaction.mutations.map((m) => m.key)
563 await api.deleteTodos(ids)
564 },
565 })
566)
567```
568
569> **Note**: QueryCollection currently auto-refetches after handlers complete. See [Controlling Refetch Behavior](#controlling-refetch-behavior) for details on this transitional behavior.
570
571### Controlling Refetch Behavior
572
573> **⚠️ Transitional API**: QueryCollection currently auto-refetches after handlers complete. This behavior is deprecated and will be removed in v1.0. See the migration notes below.
574
575#### Current Behavior (Pre-1.0)
576
577By default, QueryCollection automatically refetches after each handler completes. To **skip** auto-refetch, return `{ refetch: false }`:
578
579```typescript
580onInsert: async ({ transaction }) => {
581 await api.createTodos(transaction.mutations.map((m) => m.modified))
582
583 // Skip auto-refetch - use this when server doesn't modify the data
584 return { refetch: false }
585}
586```
587
588If you don't return `{ refetch: false }`, auto-refetch happens automatically.
589
590#### v1.0 Behavior (Future)
591
592In v1.0, auto-refetch will be **removed**. Handlers will need to explicitly call `collection.utils.refetch()` when refetching is needed:
593
594```typescript
595onInsert: async ({ transaction, collection }) => {
596 await api.createTodos(transaction.mutations.map((m) => m.modified))
597
598 // Explicitly trigger refetch when you need server state
599 await collection.utils.refetch()
600}
601```
602
603To skip refetch in v1.0, simply don't call `refetch()`:
604
605```typescript
606onInsert: async ({ transaction }) => {
607 await api.createTodos(transaction.mutations.map((m) => m.modified))
608
609 // No refetch call = no refetch (v1.0 behavior)
610}
611```
612
613#### When to Skip Refetch
614
615Skip refetching when:
616
617- You're confident the server state exactly matches what you sent (no server-side processing)
618- You're handling state updates through other mechanisms (like WebSockets or direct writes)
619- You want to optimize for fewer network requests
620
621## Utility Methods
622
623The collection provides these utility methods via `collection.utils`:
624
625- `refetch(opts?)`: Trigger a refetch of the query
626 - `opts.throwOnError`: Whether to throw an error if the refetch fails (default: `false`)
627 - Bypasses `enabled: false` to support imperative/manual refetching patterns (similar to hook `refetch()` behavior)
628 - Returns `QueryObserverResult` for inspecting the result
629
630## Direct Writes
631
632Direct writes are intended for scenarios where the normal query/mutation flow doesn't fit your needs. They write directly to the synced data store and bypass the optimistic update system. Their Query cache behavior depends on the collection's sync mode.
633
634### Understanding the Data Stores
635
636Query Collections maintain two data stores:
637
6381. **Synced Data Store** - The authoritative state synchronized with the server via `queryFn`
6392. **Optimistic Mutations Store** - Temporary changes that are applied optimistically before server confirmation
640
641Normal collection operations (insert, update, delete) create optimistic mutations that are:
642
643- Applied immediately to the UI
644- Sent to the server via persistence handlers
645- Rolled back automatically if the server request fails
646- Replaced with server data when the query refetches
647
648Direct writes bypass this system entirely and write directly to the synced data store, making them useful for handling real-time updates from alternative sources. Active on-demand queries still refetch so each scoped cache remains authoritative for its own request.
649
650### When to Use Direct Writes
651
652Direct writes should be used when:
653
654- You need to sync real-time updates from WebSockets or server-sent events
655- You're dealing with large datasets where refetching everything is too expensive
656- You receive incremental updates or server-computed field updates
657- You need to implement complex pagination or partial data loading scenarios
658
659### Individual Write Operations
660
661```typescript
662// Insert a new item directly to the synced data store
663todosCollection.utils.writeInsert({
664 id: "1",
665 text: "Buy milk",
666 completed: false,
667})
668
669// Update an existing item in the synced data store
670todosCollection.utils.writeUpdate({ id: "1", completed: true })
671
672// Delete an item from the synced data store
673todosCollection.utils.writeDelete("1")
674
675// Upsert (insert or update) in the synced data store
676todosCollection.utils.writeUpsert({
677 id: "1",
678 text: "Buy milk",
679 completed: false,
680})
681```
682
683These operations:
684
685- Write directly to the synced data store
686- Do NOT create optimistic mutations
687- Are immediately visible in the UI
688- In eager mode, update the full-result TanStack Query cache in place without refetching
689- In on-demand mode, refetch active enabled queries and remove inactive or disabled cache entries
690
691### Batch Operations
692
693The `writeBatch` method allows you to perform multiple operations atomically. Any write operations called within the callback will be collected and executed as a single transaction:
694
695```typescript
696todosCollection.utils.writeBatch(() => {
697 todosCollection.utils.writeInsert({ id: "1", text: "Buy milk" })
698 todosCollection.utils.writeInsert({ id: "2", text: "Walk dog" })
699 todosCollection.utils.writeUpdate({ id: "3", completed: true })
700 todosCollection.utils.writeDelete("4")
701})
702```
703
704### Real-World Example: WebSocket Integration
705
706```typescript
707// Handle real-time updates from WebSocket without triggering full refetches
708ws.on("todos:update", (changes) => {
709 todosCollection.utils.writeBatch(() => {
710 changes.forEach((change) => {
711 switch (change.type) {
712 case "insert":
713 todosCollection.utils.writeInsert(change.data)
714 break
715 case "update":
716 todosCollection.utils.writeUpdate(change.data)
717 break
718 case "delete":
719 todosCollection.utils.writeDelete(change.id)
720 break
721 }
722 })
723 })
724})
725```
726
727### Example: Incremental Updates
728
729When the server returns computed fields (like server-generated IDs or timestamps), you can use direct writes to sync the server response without triggering a full refetch:
730
731```typescript
732const todosCollection = createCollection(
733 queryCollectionOptions({
734 queryKey: ["todos"],
735 queryFn: fetchTodos,
736 queryClient,
737 getKey: (item) => item.id,
738
739 onInsert: async ({ transaction, collection }) => {
740 const newItems = transaction.mutations.map((m) => m.modified)
741
742 // Send to server and get back items with server-computed fields
743 const serverItems = await api.createTodos(newItems)
744
745 // Sync server-computed fields (like server-generated IDs, timestamps, etc.)
746 // to the collection's synced data store using direct writes
747 collection.utils.writeBatch(() => {
748 serverItems.forEach((serverItem) => {
749 collection.utils.writeInsert(serverItem)
750 })
751 })
752
753 // No need to refetch - we've already synced the server response via direct writes
754 // (optimistic state is automatically replaced when handler completes)
755 return { refetch: false } // Transitional pre-1.0 opt-out
756 },
757
758 onUpdate: async ({ transaction, collection }) => {
759 const updates = transaction.mutations.map((m) => ({
760 id: m.key,
761 changes: m.changes,
762 }))
763 const serverItems = await api.updateTodos(updates)
764
765 // Sync server-computed fields from the update response
766 collection.utils.writeBatch(() => {
767 serverItems.forEach((serverItem) => {
768 collection.utils.writeUpdate(serverItem)
769 })
770 })
771
772 // No refetch needed since we used direct writes
773 return { refetch: false } // Transitional pre-1.0 opt-out
774 },
775 })
776)
777
778// Usage is just like a regular collection
779todosCollection.insert({ text: "Buy milk", completed: false })
780```
781
782### Server pagination with live queries
783
784`useLiveInfiniteQuery` in React, Vue, and Svelte grows a local ordered query
785window. It does not run TanStack Query's `InfiniteQueryObserver`. Query
786Collections use `QueryObserver`, so `queryFn` receives
787`meta.loadSubsetOptions`, not `pageParam`.
788
789The previously ignored `getNextPageParam` option has been removed. Delete it
790from your hook config; passing it at runtime now throws a clear error.
791`initialPageParam` labels result pages only. It does not set a remote offset
792or server cursor.
793
794For server loading, use `syncMode: 'on-demand'` and make `queryFn` fulfill the
795requested filter, order, offset, and limit. Use a deterministic total order
796(for example, a timestamp followed by a unique ID). The loader may request a
797prefix, a suffix, a tie group, or the full filtered source. A request is not
798necessarily one UI page: the hook fetches an extra row to determine
799`hasNextPage`. Returning one capped endpoint page can incorrectly make the
800query appear exhausted even when the server has more rows.
801
802#### Endpoints with fixed-size pages
803
804If your endpoint uses page numbers, drain enough server pages to fulfill each
805request. This example assumes a zero-based page API with a fixed size of 50.
806The endpoint must apply the supplied filters and sorts **before** pagination,
807keep a consistent ordered result while its pages are read, and return
808`nextPage: null` only when it has authoritatively exhausted that result.
809This example uses offset-based pagination. `api.listPosts` translates the full
810`where` expression and `orderBy` options into the endpoint's syntax, and rejects
811unsupported expressions. The separate `cursor` hints are deliberately unused;
812cursor-based adapters must handle those hints alongside `where`, not treat them
813as already included in it. See [QueryFn and Predicate Push-Down](#queryfn-and-predicate-push-down)
814for translation helpers. Do not drop predicates or filter after paginating:
815either changes the requested window.
816
817```typescript
818import { createCollection } from '@tanstack/db'
819import { queryCollectionOptions } from '@tanstack/query-db-collection'
820
821type Post = { id: number; createdAt: number; title: string }
822const serverPageSize = 50
823
824const postsCollection = createCollection(
825 queryCollectionOptions({
826 queryKey: ['posts'],
827 queryClient,
828 syncMode: 'on-demand',
829 getKey: (post: Post) => post.id,
830 queryFn: async (ctx): Promise<Array<Post>> => {
831 const { where, orderBy, offset = 0, limit } = ctx.meta?.loadSubsetOptions ?? {}
832 const skip = offset % serverPageSize
833 let page: number | null = Math.floor(offset / serverPageSize)
834 const gathered: Array<Post> = []
835
836 while (page !== null && (limit === undefined || gathered.length < skip + limit)) {
837 ctx.signal.throwIfAborted()
838 const response: { rows: Array<Post>; nextPage: number | null } =
839 await api.listPosts({
840 page,
841 pageSize: serverPageSize,
842 where,
843 orderBy,
844 signal: ctx.signal,
845 })
846 gathered.push(...response.rows)
847 page = response.nextPage
848 }
849
850 return gathered.slice(skip, limit === undefined ? undefined : skip + limit)
851 },
852 }),
853)
854
855// React example; the collection protocol is the same for Vue and Svelte.
856const { data, fetchNextPage, hasNextPage } = useLiveInfiniteQuery(
857 (q) => q.from({ post: postsCollection })
858 .orderBy(({ post }) => post.createdAt)
859 .orderBy(({ post }) => post.id),
860 { pageSize: 20 },
861)
862```
863
864Reject failed requests instead of returning partial rows as success. An
865unlimited request must drain until the endpoint reports exhaustion. For an
866endpoint with opaque cursors, use `createCursorPager` as shown below. The hook
867does not maintain remote cursor history on its own.
868
869Manually appending rows with `writeUpsert` is a separate, lower-level loading
870strategy. It does not make an eager `queryFn` incremental: a later successful
871refetch still replaces its complete state and can remove appended rows.
872`staleTime: Infinity` does not prevent explicit refetch or invalidation.
873
874#### Endpoints with opaque cursors
875
876Query Collections ask for arbitrary windows, such as rows 40–59. An
877opaque-cursor API cannot jump to row 40. It can only fetch the first page, then
878follow the continuation token returned with each page.
879
880`createCursorPager` bridges those two protocols. It stores complete backend
881pages in your existing QueryClient and follows their cursors until it has enough
882rows for the requested `offset` and `limit`. A later request can reuse that
883fresh run of pages and fetch only the missing suffix. The hook still requests
884an extra row to decide `hasNextPage`; the pager just fulfills the resulting
885window.
886
887```typescript
888import { createCollection } from '@tanstack/db'
889import { createCursorPager, queryCollectionOptions } from '@tanstack/query-db-collection'
890
891type Post = { id: number; createdAt: number; title: string }
892
893const postsCollection = createCollection(
894 queryCollectionOptions({
895 queryClient,
896 queryKey: ['posts', 'rows'],
897 syncMode: 'on-demand',
898 getKey: (post: Post) => post.id,
899 queryFn: async (ctx) => {
900 const { where, orderBy, offset = 0, limit } = ctx.meta?.loadSubsetOptions ?? {}
901
902 // Translate every filter and sort, or reject unsupported expressions.
903 // This stable, serializable value identifies one ordered result sequence.
904 const request = api.translatePostQuery({ where, orderBy })
905
906 const pager = createCursorPager<Post>({
907 queryClient,
908 queryKey: ['posts', 'cursor-pages', request],
909 staleTime: 60_000,
910 gcTime: 5 * 60_000,
911 fetchPage: async (cursor, signal) => {
912 const response = await api.listPosts({ ...request, cursor, signal })
913
914 // Only null means that the source is exhausted.
915 return { rows: response.items, nextCursor: response.nextCursor ?? null }
916 },
917 })
918
919 return pager.read({ offset, limit }, ctx.signal)
920 },
921 }),
922)
923```
924
925##### Give each result sequence its own key
926
927The pager's query key identifies one ordered backend result, not one requested
928window. Leave `offset` and `limit` out of the key so wider reads can extend the
929same cached prefix. Include everything that changes the result—such as the
930tenant, source, filters, and order.
931
932Keep row data and cursor pages under sibling keys:
933
934```text
935['posts', 'rows'] QueryCollection row array
936['posts', 'cursor-pages', request] backend pages and cursors
937```
938
939They cannot share a key because the two cache entries have different shapes.
940Do not put cursor pages beneath the row key either: manual collection writes
941target entries under the row prefix. A shared resource prefix such as
942`['posts']` still lets you cancel or invalidate both kinds of data together.
943
944The example creates a small pager object for each `queryFn` call. Those objects
945still share cached pages and in-flight fetches through QueryClient. Each pager
946serializes its own reads. Retain one pager per result sequence only if calls
947must also share that queue or you need to call `pager.reset()` later.
948
949##### What happens when the collection asks for rows
950
951For fresh data, the pager uses every cached page it can and fetches only the
952missing suffix. `nextCursor: null` is the sole exhaustion signal: a short or
953empty page with another cursor does not end the sequence. An omitted `limit`
954drains the source; a zero limit performs no fetch. Repeated continuation tokens
955throw instead of looping forever.
956
957Query owns freshness, garbage collection, retries, and invalidation. Pass
958`staleTime` and `gcTime` to the pager or let it inherit QueryClient defaults.
959Configure retries through QueryClient defaults for the page-key prefix;
960imperative Query fetches do not retry by default. The pager keeps every page in
961its original form, so Query defaults for `maxPages` and `select` do not apply.
962
963When cached pages are stale, the next read refetches every page loaded so far,
964starting with the first. It does this even for a shallow window because old
965continuation tokens belong to the old sequence. Staleness does not start a
966background timer. The page query has no lasting observer, so its `gcTime` may
967expire while the collection's published rows remain visible.
968
969A failed read rejects rather than returning a partial window. Query keeps the
970last successful pages, so a later read can retry. Treat their rows as immutable,
971just like other Query data. `read()` returns references from the cached pages,
972not detached copies, and does not promise the same array or object identity
973across calls.
974
975##### Refresh or cancel the sequence
976
977After a mutation—or whenever you need a forced refresh—cancel the shared
978resource prefix before invalidating it:
979
980```typescript
981await queryClient.cancelQueries({ queryKey: ['posts'] })
982await queryClient.invalidateQueries({ queryKey: ['posts'] })
983```
984
985Cancelling first stops an old page append from completing after invalidation and
986marking the old sequence fresh again. It rejects readers waiting on that fetch
987with an `AbortError` and prevents a late result from entering the cache. The
988backend must honor the signal if you also want to stop its network work.
989
990Aborting the signal passed to `read()` rejects only that reader; it does not
991cancel a page fetch shared with another reader. A cancelling Query refetch moves
992waiting readers to the replacement fetch. `collection.utils.refetch()` refreshes
993the row queries but may reuse fresh cursor pages. `pager.reset()` removes one
994pager's exact page key and cancels its queued reads, but does not refresh the
995collection's row query.
996
997##### Backend contract
998
999The helper handles cursor traversal only. Your adapter must:
1000
1001- translate every requested `where` and `orderBy`, or reject unsupported
1002 expressions;
1003- apply filters and ordering before pagination;
1004- use a deterministic total order, including a unique tie-breaker;
1005- keep that ordered result consistent while its cursor sequence is read; and
1006- return `nextCursor: null` only when the result is authoritatively exhausted.
1007
1008`LoadSubsetOptions.cursor` contains query-expression hints, not the backend's
1009opaque token. `createCursorPager` therefore addresses the cursor sequence by
1010offset and deliberately does not consume those hints. No client-side pager can
1011make a stable snapshot from an endpoint whose ordering changes between pages;
1012the endpoint must define its own consistency and cursor-expiry rules.
1013
1014## Important Behaviors
1015
1016### Full State Sync
1017
1018The query collection treats the `queryFn` result as the **complete state** of the collection. This means:
1019
1020- Items present in the collection but not in the query result will be deleted
1021- Items in the query result but not in the collection will be inserted
1022- Items present in both will be updated if they differ
1023
1024This is important when the same entity type can be loaded from multiple REST
1025endpoints. For example, do not point the same Query Collection at
1026`/api/documents/preview` for one load and `/api/documents/deleted` for another
1027unless each result represents the complete state for that collection
1028scope. A narrower endpoint can otherwise remove rows that were loaded from a
1029different endpoint.
1030
1031For multiple endpoint or subset-loading use cases, choose the pattern that
1032matches your API semantics:
1033
1034- Use `syncMode: 'on-demand'` when one logical collection can serve different
1035 subsets of data. In this mode, query predicates (`where`, `orderBy`, `limit`,
1036 and `offset`) are passed to your `queryFn` via `ctx.meta.loadSubsetOptions`,
1037 letting you translate them into API parameters.
1038- Use separate Query Collections when endpoints represent distinct server scopes
1039 whose results should not replace each other. Use `unionAll` to combine them
1040 into a single query when you need a unified view across endpoints.
1041- Use direct writes such as `writeUpsert`/`writeBatch` for lower-level
1042 incremental loading when you intentionally want to merge server responses into
1043 the synced store yourself.
1044
1045### Empty Array Behavior
1046
1047When `queryFn` returns an empty array, **all items in the collection will be deleted**. This is because the collection interprets an empty array as "the server has no items".
1048
1049```typescript
1050// This will delete all items in the collection
1051queryFn: async () => []
1052```
1053
1054### Handling Partial/Incremental Fetches
1055
1056Since the query collection expects `queryFn` to return the complete state, you can handle partial fetches by merging new data with existing data:
1057
1058```typescript
1059const todosCollection = createCollection(
1060 queryCollectionOptions({
1061 queryKey: ["todos"],
1062 queryFn: async ({ queryKey }) => {
1063 // Get existing data from cache
1064 const existingData = queryClient.getQueryData(queryKey) || []
1065
1066 // Fetch only new/updated items (e.g., changes since last sync)
1067 const lastSyncTime = localStorage.getItem("todos-last-sync")
1068 const newData = await fetch(`/api/todos?since=${lastSyncTime}`).then(
1069 (r) => r.json()
1070 )
1071
1072 // Merge new data with existing data
1073 const existingMap = new Map(existingData.map((item) => [item.id, item]))
1074
1075 // Apply updates and additions
1076 newData.forEach((item) => {
1077 existingMap.set(item.id, item)
1078 })
1079
1080 // Handle deletions if your API provides them
1081 if (newData.deletions) {
1082 newData.deletions.forEach((id) => existingMap.delete(id))
1083 }
1084
1085 // Update sync time
1086 localStorage.setItem("todos-last-sync", new Date().toISOString())
1087
1088 // Return the complete merged state
1089 return Array.from(existingMap.values())
1090 },
1091 queryClient,
1092 getKey: (item) => item.id,
1093 })
1094)
1095```
1096
1097This pattern allows you to:
1098
1099- Fetch only incremental changes from your API
1100- Merge those changes with existing data
1101- Return the complete state that the collection expects
1102- Avoid the performance overhead of fetching all data every time
1103
1104### Direct Writes and Query Sync
1105
1106Direct writes update the collection immediately. In eager mode, they also patch the full-result TanStack Query cache in place.
1107
1108In on-demand mode, each Query cache entry may represent a different predicate, order, limit, or offset. A full collection snapshot cannot safely replace those scoped results. Direct writes therefore refetch active enabled queries and remove inactive or disabled entries. A successful `queryFn` result remains authoritative and may reconcile or replace a direct write.
1109
1110To handle this properly:
1111
11121. Use `{ refetch: false }` in persistence handlers to avoid the handler's additional refetch after a direct write. On-demand cache revalidation still runs.
11132. Make sure an on-demand `queryFn` returns the current server result for its pushed-down predicate, order, limit, and offset.
11143. Use eager mode when direct writes must update one complete cached result without a network request.
1115
1116## Complete Direct Write API Reference
1117
1118All direct write methods are available on `collection.utils`:
1119
1120- `writeInsert(data)`: Insert one or more items directly
1121- `writeUpdate(data)`: Update one or more items directly
1122- `writeDelete(keys)`: Delete one or more items directly
1123- `writeUpsert(data)`: Insert or update one or more items directly
1124- `writeBatch(callback)`: Perform multiple operations atomically
1125- `refetch(opts?)`: Trigger a refetch of the query
1126
1127## QueryFn and Predicate Push-Down
1128
1129When using `syncMode: 'on-demand'`, the collection automatically pushes down query predicates (where clauses, orderBy, limit, and offset) to your `queryFn`. This allows you to fetch only the data needed for each specific query, rather than fetching the entire dataset.
1130
1131### How LoadSubsetOptions Are Passed
1132
1133LoadSubsetOptions are passed to your `queryFn` via the query context's `meta` property:
1134
1135```typescript
1136queryFn: async (ctx) => {
1137 // Extract LoadSubsetOptions from the context
1138 const { limit, offset, where, orderBy } = ctx.meta.loadSubsetOptions
1139
1140 // Use these to fetch only the data you need
1141 // - where: filter expression (AST)
1142 // - orderBy: sort expression (AST)
1143 // - limit: maximum number of rows
1144 // - offset: number of rows to skip (for pagination)
1145 // ...
1146}
1147```
1148
1149The `where` and `orderBy` fields are expression trees (AST - Abstract Syntax Tree) that need to be parsed. TanStack DB provides helper functions to make this easy.
1150
1151### Expression Helpers
1152
1153```typescript
1154import {
1155 parseWhereExpression,
1156 parseOrderByExpression,
1157 extractSimpleComparisons,
1158 parseLoadSubsetOptions,
1159} from '@tanstack/db'
1160// Or from '@tanstack/query-db-collection' (re-exported for convenience)
1161```
1162
1163These helpers allow you to parse expression trees without manually traversing complex AST structures.
1164
1165### Quick Start: Simple REST API
1166
1167```typescript
1168import { createCollection } from '@tanstack/react-db'
1169import { queryCollectionOptions } from '@tanstack/query-db-collection'
1170import { parseLoadSubsetOptions } from '@tanstack/db'
1171import { QueryClient } from '@tanstack/query-core'
1172
1173const queryClient = new QueryClient()
1174
1175const productsCollection = createCollection(
1176 queryCollectionOptions({
1177 id: 'products',
1178 queryKey: ['products'],
1179 queryClient,
1180 getKey: (item) => item.id,
1181 syncMode: 'on-demand', // Enable predicate push-down
1182
1183 queryFn: async (ctx) => {
1184 const { limit, offset, where, orderBy } = ctx.meta.loadSubsetOptions
1185
1186 // Parse the expressions into simple format
1187 const parsed = parseLoadSubsetOptions({ where, orderBy, limit })
1188
1189 // Build query parameters from parsed filters
1190 const params = new URLSearchParams()
1191
1192 // Add filters
1193 parsed.filters.forEach(({ field, operator, value }) => {
1194 const fieldName = field.join('.')
1195 if (operator === 'eq') {
1196 params.set(fieldName, String(value))
1197 } else if (operator === 'lt') {
1198 params.set(`${fieldName}_lt`, String(value))
1199 } else if (operator === 'gt') {
1200 params.set(`${fieldName}_gt`, String(value))
1201 }
1202 })
1203
1204 // Add sorting
1205 if (parsed.sorts.length > 0) {
1206 const sortParam = parsed.sorts
1207 .map(s => `${s.field.join('.')}:${s.direction}`)
1208 .join(',')
1209 params.set('sort', sortParam)
1210 }
1211
1212 // Add limit
1213 if (parsed.limit) {
1214 params.set('limit', String(parsed.limit))
1215 }
1216
1217 // Add offset for pagination
1218 if (offset) {
1219 params.set('offset', String(offset))
1220 }
1221
1222 const response = await fetch(`/api/products?${params}`)
1223 return response.json()
1224 },
1225 })
1226)
1227
1228// Usage with live queries
1229import { createLiveQueryCollection } from '@tanstack/react-db'
1230import { eq, lt, and } from '@tanstack/db'
1231
1232const affordableElectronics = createLiveQueryCollection({
1233 query: (q) =>
1234 q.from({ product: productsCollection })
1235 .where(({ product }) => and(
1236 eq(product.category, 'electronics'),
1237 lt(product.price, 100)
1238 ))
1239 .orderBy(({ product }) => product.price, 'asc')
1240 .limit(10)
1241 .select(({ product }) => product)
1242})
1243
1244// This triggers a queryFn call with:
1245// GET /api/products?category=electronics&price_lt=100&sort=price:asc&limit=10
1246// When paginating, offset is included: &offset=20
1247```
1248
1249### Custom Handlers for Complex APIs
1250
1251For APIs with specific formats, use custom handlers:
1252
1253```typescript
1254queryFn: async (ctx) => {
1255 const { where, orderBy, limit } = ctx.meta.loadSubsetOptions
1256
1257 // Use custom handlers to match your API's format
1258 const filters = parseWhereExpression(where, {
1259 handlers: {
1260 eq: (field, value) => ({
1261 field: field.join('.'),
1262 op: 'equals',
1263 value
1264 }),
1265 lt: (field, value) => ({
1266 field: field.join('.'),
1267 op: 'lessThan',
1268 value
1269 }),
1270 and: (...conditions) => ({
1271 operator: 'AND',
1272 conditions
1273 }),
1274 or: (...conditions) => ({
1275 operator: 'OR',
1276 conditions
1277 }),
1278 }
1279 })
1280
1281 const sorts = parseOrderByExpression(orderBy)
1282
1283 return api.query({
1284 filters,
1285 sort: sorts.map(s => ({
1286 field: s.field.join('.'),
1287 order: s.direction.toUpperCase()
1288 })),
1289 limit
1290 })
1291}
1292```
1293
1294### GraphQL Example
1295
1296```typescript
1297queryFn: async (ctx) => {
1298 const { where, orderBy, limit } = ctx.meta.loadSubsetOptions
1299
1300 // Convert to a GraphQL where clause format
1301 const whereClause = parseWhereExpression(where, {
1302 handlers: {
1303 eq: (field, value) => ({
1304 [field.join('_')]: { _eq: value }
1305 }),
1306 lt: (field, value) => ({
1307 [field.join('_')]: { _lt: value }
1308 }),
1309 and: (...conditions) => ({ _and: conditions }),
1310 or: (...conditions) => ({ _or: conditions }),
1311 }
1312 })
1313
1314 // Convert to a GraphQL order_by format
1315 const sorts = parseOrderByExpression(orderBy)
1316 const orderByClause = sorts.map(s => ({
1317 [s.field.join('_')]: s.direction
1318 }))
1319
1320 const { data } = await graphqlClient.query({
1321 query: gql`
1322 query GetProducts($where: product_bool_exp, $orderBy: [product_order_by!], $limit: Int) {
1323 product(where: $where, order_by: $orderBy, limit: $limit) {
1324 id
1325 name
1326 category
1327 price
1328 }
1329 }
1330 `,
1331 variables: {
1332 where: whereClause,
1333 orderBy: orderByClause,
1334 limit
1335 }
1336 })
1337
1338 return data.product
1339}
1340```
1341
1342### Expression Helper API Reference
1343
1344#### `parseLoadSubsetOptions(options)`
1345
1346Convenience function that parses all LoadSubsetOptions at once. Good for simple use cases.
1347
1348```typescript
1349const { filters, sorts, limit, offset } = parseLoadSubsetOptions(ctx.meta?.loadSubsetOptions)
1350// filters: [{ field: ['category'], operator: 'eq', value: 'electronics' }]
1351// sorts: [{ field: ['price'], direction: 'asc', nulls: 'last' }]
1352// limit: 10
1353// offset: 20 (for pagination)
1354```
1355
1356#### `parseWhereExpression(expr, options)`
1357
1358Parses a WHERE expression using custom handlers for each operator. Use this for complete control over the output format.
1359
1360```typescript
1361const filters = parseWhereExpression(where, {
1362 handlers: {
1363 eq: (field, value) => ({ [field.join('.')]: value }),
1364 lt: (field, value) => ({ [`${field.join('.')}_lt`]: value }),
1365 and: (...filters) => Object.assign({}, ...filters)
1366 },
1367 onUnknownOperator: (operator, args) => {
1368 console.warn(`Unsupported operator: ${operator}`)
1369 return null
1370 }
1371})
1372```
1373
1374#### `parseOrderByExpression(orderBy)`
1375
1376Parses an ORDER BY expression into a simple array.
1377
1378```typescript
1379const sorts = parseOrderByExpression(orderBy)
1380// Returns: [{ field: ['price'], direction: 'asc', nulls: 'last' }]
1381```
1382
1383#### `extractSimpleComparisons(expr)`
1384
1385Extracts simple AND-ed comparisons from a WHERE expression. Note: Only works for simple AND conditions.
1386
1387```typescript
1388const comparisons = extractSimpleComparisons(where)
1389// Returns: [
1390// { field: ['category'], operator: 'eq', value: 'electronics' },
1391// { field: ['price'], operator: 'lt', value: 100 }
1392// ]
1393```
1394
1395### Supported Operators
1396
1397- `eq` - Equality (=)
1398- `gt` - Greater than (>)
1399- `gte` - Greater than or equal (>=)
1400- `lt` - Less than (<)
1401- `lte` - Less than or equal (<=)
1402- `and` - Logical AND
1403- `or` - Logical OR
1404- `in` - IN clause
1405
1406### Using Query Key Builders
1407
1408Create different cache entries for different filter combinations:
1409
1410```typescript
1411const productsCollection = createCollection(
1412 queryCollectionOptions({
1413 id: 'products',
1414 // Dynamic query key based on filters
1415 queryKey: (opts) => {
1416 const parsed = parseLoadSubsetOptions(opts)
1417 const cacheKey = ['products']
1418
1419 parsed.filters.forEach(f => {
1420 cacheKey.push(`${f.field.join('.')}-${f.operator}-${f.value}`)
1421 })
1422
1423 if (parsed.limit) {
1424 cacheKey.push(`limit-${parsed.limit}`)
1425 }
1426
1427 return cacheKey
1428 },
1429 queryClient,
1430 getKey: (item) => item.id,
1431 syncMode: 'on-demand',
1432 queryFn: async (ctx) => { /* ... */ },
1433 })
1434)
1435```
1436
1437#### Query Key Prefix Convention
1438
1439When using a function-based `queryKey`, all derived keys **must extend the base key as a prefix**. The base key is what your function returns when called with no options (`queryKey({})`).
1440
1441TanStack Query uses prefix matching for cache operations internally. The query collection relies on this to find all cache entries belonging to a collection — including stale entries from destroyed query observers that are still held in cache due to `gcTime`. If derived keys don't share the base prefix, cache updates may silently miss entries, leading to stale data.
1442
1443```typescript
1444// ✅ Correct: base key ['products'] is a prefix of all derived keys
1445queryKey: (opts) => {
1446 if (opts.where) {
1447 return ['products', JSON.stringify(opts.where)]
1448 }
1449 return ['products']
1450}
1451
1452// ❌ Wrong: base key ['products-all'] is NOT a prefix of ['products-filtered', ...]
1453queryKey: (opts) => {
1454 if (opts.where) {
1455 return ['products-filtered', JSON.stringify(opts.where)]
1456 }
1457 return ['products-all']
1458}
1459```
1460
1461### Tips
1462
14631. **Start with `parseLoadSubsetOptions`** for simple use cases
14642. **Use custom handlers** via `parseWhereExpression` for APIs with specific formats
14653. **Handle unsupported operators** with the `onUnknownOperator` callback
14664. **Log parsed results** during development to verify correctness