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