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

BaseCollectionConfig.md

483 lines11.3 KB

1---
2id: BaseCollectionConfig
3title: BaseCollectionConfig
4---
5​
6Defined in: [packages/db/src/types.ts:762](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L762)
7​
8## Extended by
9​
10- [`CollectionConfig`](CollectionConfig.md)
11- [`LocalStorageCollectionConfig`](LocalStorageCollectionConfig.md)
12- [`IndexedDBCollectionConfig`](IndexedDBCollectionConfig.md)
13​
14## Type Parameters
15​
16### T
17​
18`T` *extends* `object` = `Record`\<`string`, `unknown`\>
19​
20### TKey
21​
22`TKey` *extends* `string` \| `number` = `string` \| `number`
23​
24### TSchema
25​
26`TSchema` *extends* `StandardSchemaV1` = `never`
27​
28### TUtils
29​
30`TUtils` *extends* [`UtilsRecord`](../type-aliases/UtilsRecord.md) = [`UtilsRecord`](../type-aliases/UtilsRecord.md)
31​
32### TReturn
33​
34`TReturn` = `any`
35​
36## Properties
37​
38### autoIndex?
39​
40```ts
41optional autoIndex: "eager" | "off";
42```
43​
44Defined in: [packages/db/src/types.ts:816](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L816)
45​
46Auto-indexing mode for the collection.
47When enabled, indexes will be automatically created for simple where expressions.
48​
49#### Default
50​
51```ts
52"off"
53```
54​
55#### Description
56​
57- "off": No automatic indexing (default). Use explicit indexes for better bundle size.
58- "eager": Automatically create indexes for simple where expressions in subscribeChanges.
59 Requires setting defaultIndexType.
60​
61***
62​
63### compare()?
64​
65```ts
66optional compare: (x, y) => number;
67```
68​
69Defined in: [packages/db/src/types.ts:841](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L841)
70​
71Optional function to compare two items.
72This is used to order the items in the collection.
73​
74#### Parameters
75​
76##### x
77​
78`T`
79​
80The first item to compare
81​
82##### y
83​
84`T`
85​
86The second item to compare
87​
88#### Returns
89​
90`number`
91​
92A number indicating the order of the items
93​
94#### Example
95​
96```ts
97// For a collection with a 'createdAt' field
98compare: (x, y) => x.createdAt.getTime() - y.createdAt.getTime()
99```
100​
101***
102​
103### defaultIndexType?
104​
105```ts
106optional defaultIndexType: IndexConstructor<TKey>;
107```
108​
109Defined in: [packages/db/src/types.ts:830](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L830)
110​
111Default index type to use when creating indexes without an explicit type.
112Required for auto-indexing. Import from '@tanstack/db'.
113​
114#### Example
115​
116```ts
117import { BasicIndex } from '@tanstack/db'
118const collection = createCollection({
119 defaultIndexType: BasicIndex,
120 autoIndex: 'eager',
121 // ...
122})
123```
124​
125***
126​
127### defaultStringCollation?
128​
129```ts
130optional defaultStringCollation: StringCollationConfig;
131```
132​
133Defined in: [packages/db/src/types.ts:1036](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1036)
134​
135Specifies how to compare data in the collection.
136This should be configured to match data ordering on the backend.
137E.g., when using the Electric DB collection these options
138 should match the database's collation settings.
139​
140***
141​
142### gcTime?
143​
144```ts
145optional gcTime: number;
146```
147​
148Defined in: [packages/db/src/types.ts:795](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L795)
149​
150Time in milliseconds after which the collection will be garbage collected
151when it has no active subscribers. Defaults to 5 minutes (300000ms).
152Sync started without subscribers gets a minimum 50ms grace period.
153Pending preloads retain the collection until they settle. Preloading ready
154data refreshes the retention period. A non-positive or non-finite value
155disables automatic garbage collection.
156​
157***
158​
159### getKey()
160​
161```ts
162getKey: (item) => TKey;
163```
164​
165Defined in: [packages/db/src/types.ts:786](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L786)
166​
167Function to extract the ID from an object
168This is required for update/delete operations which now only accept IDs
169​
170#### Parameters
171​
172##### item
173​
174`T`
175​
176The item to extract the ID from
177​
178#### Returns
179​
180`TKey`
181​
182The ID string for the item
183​
184#### Example
185​
186```ts
187// For a collection with a 'uuid' field as the primary key
188getKey: (item) => item.uuid
189```
190​
191***
192​
193### id?
194​
195```ts
196optional id: string;
197```
198​
199Defined in: [packages/db/src/types.ts:775](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L775)
200​
201***
202​
203### onDelete?
204​
205```ts
206optional onDelete:
207 | DeleteMutationFn<T, TKey, TUtils, void>
208| DeleteMutationFn<T, TKey, TUtils, TReturn>;
209```
210​
211Defined in: [packages/db/src/types.ts:1025](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1025)
212​
213Optional asynchronous handler function called before a delete operation
214Returning a value is deprecated; coordinate synchronization through collection utilities instead.
215​
216#### Examples
217​
218```ts
219// Basic delete handler
220onDelete: async ({ transaction, collection }) => {
221 const deletedKey = transaction.mutations[0].key
222 await api.deleteTodo(deletedKey)
224```
225​
226```ts
227// Delete handler with refetch (Query Collection)
228onDelete: async ({ transaction, collection }) => {
229 const keysToDelete = transaction.mutations.map(m => m.key)
230 await api.deleteTodos(keysToDelete)
231 // Trigger refetch to sync server state
232 await collection.utils.refetch()
233 // Prevent the pre-1.0 compatibility wrapper from refetching again.
234 return { refetch: false }
236```
237​
238```ts
239// Delete handler with sync wait (Electric Collection)
240onDelete: async ({ transaction, collection }) => {
241 const mutation = transaction.mutations[0]
242 const result = await api.deleteTodo(mutation.original.id)
243 // Wait for txid to sync
244 await collection.utils.awaitTxId(result.txid)
246```
247​
248```ts
249// Delete handler with confirmation
250onDelete: async ({ transaction, collection }) => {
251 const mutation = transaction.mutations[0]
252 const shouldDelete = await confirmDeletion(mutation.original)
253 if (!shouldDelete) {
254 throw new Error('Delete cancelled by user')
255 }
256 await api.deleteTodo(mutation.original.id)
258```
259​
260```ts
261// Delete handler with optimistic rollback
262onDelete: async ({ transaction, collection }) => {
263 const mutation = transaction.mutations[0]
264 try {
265 await api.deleteTodo(mutation.original.id)
266 } catch (error) {
267 // Transaction will automatically rollback optimistic changes
268 console.error('Delete failed, rolling back:', error)
269 throw error
270 }
272```
273​
274***
275​
276### onInsert?
277​
278```ts
279optional onInsert:
280 | InsertMutationFn<T, TKey, TUtils, void>
281| InsertMutationFn<T, TKey, TUtils, TReturn>;
282```
283​
284Defined in: [packages/db/src/types.ts:904](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L904)
285​
286Optional asynchronous handler function called before an insert operation
287Returning a value is deprecated; coordinate synchronization through collection utilities instead.
288​
289#### Examples
290​
291```ts
292// Basic insert handler
293onInsert: async ({ transaction, collection }) => {
294 const newItem = transaction.mutations[0].modified
295 await api.createTodo(newItem)
297```
298​
299```ts
300// Insert handler with refetch (Query Collection)
301onInsert: async ({ transaction, collection }) => {
302 const newItem = transaction.mutations[0].modified
303 await api.createTodo(newItem)
304 // Trigger refetch to sync server state
305 await collection.utils.refetch()
306 // Prevent the pre-1.0 compatibility wrapper from refetching again.
307 return { refetch: false }
309```
310​
311```ts
312// Insert handler with sync wait (Electric Collection)
313onInsert: async ({ transaction, collection }) => {
314 const newItem = transaction.mutations[0].modified
315 const result = await api.createTodo(newItem)
316 // Wait for txid to sync
317 await collection.utils.awaitTxId(result.txid)
319```
320​
321```ts
322// Insert handler with multiple items
323onInsert: async ({ transaction, collection }) => {
324 const items = transaction.mutations.map(m => m.modified)
325 await api.createTodos(items)
326 // Refetch to get updated data from server
327 await collection.utils.refetch()
328 return { refetch: false }
330```
331​
332```ts
333// Insert handler with error handling
334onInsert: async ({ transaction, collection }) => {
335 try {
336 const newItem = transaction.mutations[0].modified
337 await api.createTodo(newItem)
338 } catch (error) {
339 console.error('Insert failed:', error)
340 throw error // This will cause the transaction to rollback
341 }
343```
344​
345***
346​
347### onUpdate?
348​
349```ts
350optional onUpdate:
351 | UpdateMutationFn<T, TKey, TUtils, void>
352| UpdateMutationFn<T, TKey, TUtils, TReturn>;
353```
354​
355Defined in: [packages/db/src/types.ts:966](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L966)
356​
357Optional asynchronous handler function called before an update operation
358Returning a value is deprecated; coordinate synchronization through collection utilities instead.
359​
360#### Examples
361​
362```ts
363// Basic update handler
364onUpdate: async ({ transaction, collection }) => {
365 const updatedItem = transaction.mutations[0].modified
366 await api.updateTodo(updatedItem.id, updatedItem)
368```
369​
370```ts
371// Update handler with refetch (Query Collection)
372onUpdate: async ({ transaction, collection }) => {
373 const mutation = transaction.mutations[0]
374 const changes = mutation.changes // Only the changed fields
375 await api.updateTodo(mutation.original.id, changes)
376 // Trigger refetch to sync server state
377 await collection.utils.refetch()
378 // Prevent the pre-1.0 compatibility wrapper from refetching again.
379 return { refetch: false }
381```
382​
383```ts
384// Update handler with sync wait (Electric Collection)
385onUpdate: async ({ transaction, collection }) => {
386 const mutation = transaction.mutations[0]
387 const result = await api.updateTodo(mutation.original.id, mutation.changes)
388 // Wait for txid to sync
389 await collection.utils.awaitTxId(result.txid)
391```
392​
393```ts
394// Update handler with multiple items
395onUpdate: async ({ transaction, collection }) => {
396 const updates = transaction.mutations.map(m => ({
397 id: m.key,
398 changes: m.changes
399 }))
400 await api.updateTodos(updates)
401 await collection.utils.refetch()
402 return { refetch: false }
404```
405​
406```ts
407// Update handler with optimistic rollback
408onUpdate: async ({ transaction, collection }) => {
409 const mutation = transaction.mutations[0]
410 try {
411 await api.updateTodo(mutation.original.id, mutation.changes)
412 } catch (error) {
413 // Transaction will automatically rollback optimistic changes
414 console.error('Update failed, rolling back:', error)
415 throw error
416 }
418```
419​
420***
421​
422### schema?
423​
424```ts
425optional schema: TSchema;
426```
427​
428Defined in: [packages/db/src/types.ts:776](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L776)
429​
430***
431​
432### startSync?
433​
434```ts
435optional startSync: boolean;
436```
437​
438Defined in: [packages/db/src/types.ts:806](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L806)
439​
440Whether to eagerly start syncing on collection creation.
441When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches.
442​
443Note: Even with startSync=true, collections will pause syncing when there are no active
444subscribers (typically when components querying the collection unmount), resuming when new
445subscribers attach. This preserves normal staleTime/gcTime behavior.
446​
447#### Default
448​
449```ts
450false
451```
452​
453***
454​
455### syncMode?
456​
457```ts
458optional syncMode: SyncMode;
459```
460​
461Defined in: [packages/db/src/types.ts:850](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L850)
462​
463The mode of sync to use for the collection.
464​
465#### Default
466​
467`eager`
468​
469#### Description
470​
471- `eager`: syncs all data immediately on preload
472- `on-demand`: syncs data in incremental snapshots when the collection is queried
473The exact implementation of the sync mode is up to the sync implementation.
474​
475***
476​
477### utils?
478​
479```ts
480optional utils: TUtils;
481```
482​
483Defined in: [packages/db/src/types.ts:1038](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1038)