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

query-collection.md

351 lines11.6 KB

1---
2title: Query Collection
3---
4​
5# Query Collection
6​
7Query collections provide seamless integration between TanStack DB and TanStack Query, enabling automatic synchronization between your local database and remote data sources.
8​
9## Overview
10​
11The `@tanstack/query-db-collection` package allows you to create collections that:
12- Automatically sync with remote data via TanStack Query
13- Support optimistic updates with automatic rollback on errors
14- Handle persistence through customizable mutation handlers
15- Provide direct write capabilities for directly writing to the sync store
16​
17## Installation
18​
19```bash
20npm install @tanstack/query-db-collection @tanstack/query-core @tanstack/db
21```
22​
23## Basic Usage
24​
25```typescript
26import { QueryClient } from '@tanstack/query-core'
27import { createCollection } from '@tanstack/db'
28import { queryCollectionOptions } from '@tanstack/query-db-collection'
29​
30const queryClient = new QueryClient()
31​
32const todosCollection = createCollection(
33 queryCollectionOptions({
34 queryKey: ['todos'],
35 queryFn: async () => {
36 const response = await fetch('/api/todos')
37 return response.json()
38 },
39 queryClient,
40 getKey: (item) => item.id,
41 })
43```
44​
45## Configuration Options
46​
47The `queryCollectionOptions` function accepts the following options:
48​
49### Required Options
50​
51- `queryKey`: The query key for TanStack Query
52- `queryFn`: Function that fetches data from the server
53- `queryClient`: TanStack Query client instance
54- `getKey`: Function to extract the unique key from an item
55​
56### Query Options
57​
58- `select`: Function that lets extract array items when they’re wrapped with metadata
59- `enabled`: Whether the query should automatically run (default: `true`)
60- `refetchInterval`: Refetch interval in milliseconds
61- `retry`: Retry configuration for failed queries
62- `retryDelay`: Delay between retries
63- `staleTime`: How long data is considered fresh
64- `meta`: Optional metadata that will be passed to the query function context
65​
66### Collection Options
67​
68- `id`: Unique identifier for the collection
69- `schema`: Schema for validating items
70- `sync`: Custom sync configuration
71- `startSync`: Whether to start syncing immediately (default: `true`)
72​
73### Persistence Handlers
74​
75- `onInsert`: Handler called before insert operations
76- `onUpdate`: Handler called before update operations
77- `onDelete`: Handler called before delete operations
78​
79## Persistence Handlers
80​
81You can define handlers that are called when mutations occur. These handlers can persist changes to your backend and control whether the query should refetch after the operation:
82​
83```typescript
84const todosCollection = createCollection(
85 queryCollectionOptions({
86 queryKey: ['todos'],
87 queryFn: fetchTodos,
88 queryClient,
89 getKey: (item) => item.id,
91 onInsert: async ({ transaction }) => {
92 const newItems = transaction.mutations.map(m => m.modified)
93 await api.createTodos(newItems)
94 // Returning nothing or { refetch: true } will trigger a refetch
95 // Return { refetch: false } to skip automatic refetch
96 },
98 onUpdate: async ({ transaction }) => {
99 const updates = transaction.mutations.map(m => ({
100 id: m.key,
101 changes: m.changes
102 }))
103 await api.updateTodos(updates)
104 },
106 onDelete: async ({ transaction }) => {
107 const ids = transaction.mutations.map(m => m.key)
108 await api.deleteTodos(ids)
109 }
110 })
112```
113​
114### Controlling Refetch Behavior
115​
116By default, after any persistence handler (`onInsert`, `onUpdate`, or `onDelete`) completes successfully, the query will automatically refetch to ensure the local state matches the server state.
117​
118You can control this behavior by returning an object with a `refetch` property:
119​
120```typescript
121onInsert: async ({ transaction }) => {
122 await api.createTodos(transaction.mutations.map(m => m.modified))
124 // Skip the automatic refetch
125 return { refetch: false }
127```
128​
129This is useful when:
130- You're confident the server state matches what you sent
131- You want to avoid unnecessary network requests
132- You're handling state updates through other mechanisms (like WebSockets)
133​
134## Utility Methods
135​
136The collection provides these utility methods via `collection.utils`:
137​
138- `refetch()`: Manually trigger a refetch of the query
139​
140## Direct Writes
141​
142Direct writes are intended for scenarios where the normal query/mutation flow doesn't fit your needs. They allow you to write directly to the synced data store, bypassing the optimistic update system and query refetch mechanism.
143​
144### Understanding the Data Stores
145​
146Query Collections maintain two data stores:
1471. **Synced Data Store** - The authoritative state synchronized with the server via `queryFn`
1482. **Optimistic Mutations Store** - Temporary changes that are applied optimistically before server confirmation
149​
150Normal collection operations (insert, update, delete) create optimistic mutations that are:
151- Applied immediately to the UI
152- Sent to the server via persistence handlers
153- Rolled back automatically if the server request fails
154- Replaced with server data when the query refetches
155​
156Direct writes bypass this system entirely and write directly to the synced data store, making them ideal for handling real-time updates from alternative sources.
157​
158### When to Use Direct Writes
159​
160Direct writes should be used when:
161- You need to sync real-time updates from WebSockets or server-sent events
162- You're dealing with large datasets where refetching everything is too expensive
163- You receive incremental updates or server-computed field updates
164- You need to implement complex pagination or partial data loading scenarios
165​
166### Individual Write Operations
167​
168```typescript
169// Insert a new item directly to the synced data store
170todosCollection.utils.writeInsert({ id: '1', text: 'Buy milk', completed: false })
171​
172// Update an existing item in the synced data store
173todosCollection.utils.writeUpdate({ id: '1', completed: true })
174​
175// Delete an item from the synced data store
176todosCollection.utils.writeDelete('1')
177​
178// Upsert (insert or update) in the synced data store
179todosCollection.utils.writeUpsert({ id: '1', text: 'Buy milk', completed: false })
180```
181​
182These operations:
183- Write directly to the synced data store
184- Do NOT create optimistic mutations
185- Do NOT trigger automatic query refetches
186- Update the TanStack Query cache immediately
187- Are immediately visible in the UI
188​
189### Batch Operations
190​
191The `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:
192​
193```typescript
194todosCollection.utils.writeBatch(() => {
195 todosCollection.utils.writeInsert({ id: '1', text: 'Buy milk' })
196 todosCollection.utils.writeInsert({ id: '2', text: 'Walk dog' })
197 todosCollection.utils.writeUpdate({ id: '3', completed: true })
198 todosCollection.utils.writeDelete('4')
199})
200```
201​
202### Real-World Example: WebSocket Integration
203​
204```typescript
205// Handle real-time updates from WebSocket without triggering full refetches
206ws.on('todos:update', (changes) => {
207 todosCollection.utils.writeBatch(() => {
208 changes.forEach(change => {
209 switch (change.type) {
210 case 'insert':
211 todosCollection.utils.writeInsert(change.data)
212 break
213 case 'update':
214 todosCollection.utils.writeUpdate(change.data)
215 break
216 case 'delete':
217 todosCollection.utils.writeDelete(change.id)
218 break
219 }
220 })
221 })
222})
223```
224​
225### Example: Incremental Updates
226​
227```typescript
228// Handle server responses after mutations without full refetch
229const createTodo = async (todo) => {
230 // Optimistically add the todo
231 const tempId = crypto.randomUUID()
232 todosCollection.insert({ ...todo, id: tempId })
234 try {
235 // Send to server
236 const serverTodo = await api.createTodo(todo)
238 // Sync the server response (with server-generated ID and timestamps)
239 // without triggering a full collection refetch
240 todosCollection.utils.writeBatch(() => {
241 todosCollection.utils.writeDelete(tempId)
242 todosCollection.utils.writeInsert(serverTodo)
243 })
244 } catch (error) {
245 // Rollback happens automatically
246 throw error
247 }
249```
250​
251### Example: Large Dataset Pagination
252​
253```typescript
254// Load additional pages without refetching existing data
255const loadMoreTodos = async (page) => {
256 const newTodos = await api.getTodos({ page, limit: 50 })
258 // Add new items without affecting existing ones
259 todosCollection.utils.writeBatch(() => {
260 newTodos.forEach(todo => {
261 todosCollection.utils.writeInsert(todo)
262 })
263 })
265```
266​
267## Important Behaviors
268​
269### Full State Sync
270​
271The query collection treats the `queryFn` result as the **complete state** of the collection. This means:
272​
273- Items present in the collection but not in the query result will be deleted
274- Items in the query result but not in the collection will be inserted
275- Items present in both will be updated if they differ
276​
277### Empty Array Behavior
278​
279When `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".
280​
281```typescript
282// This will delete all items in the collection
283queryFn: async () => []
284```
285​
286### Handling Partial/Incremental Fetches
287​
288Since the query collection expects `queryFn` to return the complete state, you can handle partial fetches by merging new data with existing data:
289​
290```typescript
291const todosCollection = createCollection(
292 queryCollectionOptions({
293 queryKey: ['todos'],
294 queryFn: async ({ queryKey }) => {
295 // Get existing data from cache
296 const existingData = queryClient.getQueryData(queryKey) || []
298 // Fetch only new/updated items (e.g., changes since last sync)
299 const lastSyncTime = localStorage.getItem('todos-last-sync')
300 const newData = await fetch(`/api/todos?since=${lastSyncTime}`).then(r => r.json())
302 // Merge new data with existing data
303 const existingMap = new Map(existingData.map(item => [item.id, item]))
305 // Apply updates and additions
306 newData.forEach(item => {
307 existingMap.set(item.id, item)
308 })
310 // Handle deletions if your API provides them
311 if (newData.deletions) {
312 newData.deletions.forEach(id => existingMap.delete(id))
313 }
315 // Update sync time
316 localStorage.setItem('todos-last-sync', new Date().toISOString())
318 // Return the complete merged state
319 return Array.from(existingMap.values())
320 },
321 queryClient,
322 getKey: (item) => item.id,
323 })
325```
326​
327This pattern allows you to:
328- Fetch only incremental changes from your API
329- Merge those changes with existing data
330- Return the complete state that the collection expects
331- Avoid the performance overhead of fetching all data every time
332​
333### Direct Writes and Query Sync
334​
335Direct writes update the collection immediately and also update the TanStack Query cache. However, they do not prevent the normal query sync behavior. If your `queryFn` returns data that conflicts with your direct writes, the query data will take precedence.
336​
337To handle this properly:
3381. Use `{ refetch: false }` in your persistence handlers when using direct writes
3392. Set appropriate `staleTime` to prevent unnecessary refetches
3403. Design your `queryFn` to be aware of incremental updates (e.g., only fetch new data)
341​
342## Complete Direct Write API Reference
343​
344All direct write methods are available on `collection.utils`:
345​
346- `writeInsert(data)`: Insert one or more items directly
347- `writeUpdate(data)`: Update one or more items directly
348- `writeDelete(keys)`: Delete one or more items directly
349- `writeUpsert(data)`: Insert or update one or more items directly
350- `writeBatch(callback)`: Perform multiple operations atomically
351- `refetch()`: Manually trigger a refetch of the query