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