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

CollectionConfig.md

535 lines12.7 KB

1---
2id: CollectionConfig
3title: CollectionConfig
4---
5​
6Defined in: [packages/db/src/types.ts:1142](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1142)
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: "eager" | "off";
36```
37​
38Defined in: [packages/db/src/types.ts:937](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L937)
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:962](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L962)
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:951](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L951)
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:1137](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1137)
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:916](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L916)
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 handoff grace period
163until a subscriber attaches. After the last subscriber leaves, gcTime
164applies without that startup minimum.
165Pending preloads retain the collection until they settle. Preloading ready
166data refreshes the retention period. A persisting transaction that touches
167the collection also retains it, and the period starts again when the last
168one completes or fails, preserving any remaining startup grace. Pending
169manual transactions do not retain it; keep a subscription for draft
170visibility until commit or rollback. Rolling
171back a manual transaction that stayed pending preserves the existing GC
172deadline. Cleanup runs at a host idle opportunity after the delay.
173A non-positive or non-finite value
174disables automatic garbage collection.
175​
176#### Inherited from
177​
178[`BaseCollectionConfig`](BaseCollectionConfig.md).[`gcTime`](BaseCollectionConfig.md#gctime)
179​
180***
181​
182### getKey()
183​
184```ts
185getKey: (item) => TKey;
186```
187​
188Defined in: [packages/db/src/types.ts:898](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L898)
189​
190Function to extract the ID from an object
191This is required for update/delete operations which now only accept IDs
192​
193#### Parameters
194​
195##### item
196​
197`T`
198​
199The item to extract the ID from
200​
201#### Returns
202​
203`TKey`
204​
205The ID string for the item
206​
207#### Example
208​
209```ts
210// For a collection with a 'uuid' field as the primary key
211getKey: (item) => item.uuid
212```
213​
214#### Inherited from
215​
216[`BaseCollectionConfig`](BaseCollectionConfig.md).[`getKey`](BaseCollectionConfig.md#getkey)
217​
218***
219​
220### id?
221​
222```ts
223optional id: string;
224```
225​
226Defined in: [packages/db/src/types.ts:887](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L887)
227​
228#### Inherited from
229​
230[`BaseCollectionConfig`](BaseCollectionConfig.md).[`id`](BaseCollectionConfig.md#id)
231​
232***
233​
234### onDelete?
235​
236```ts
237optional onDelete: DeleteMutationFn<T, TKey, TUtils>;
238```
239​
240Defined in: [packages/db/src/types.ts:1129](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1129)
241​
242Optional asynchronous handler function called before a delete operation
243​
244#### Examples
245​
246```ts
247// Basic delete handler
248onDelete: async ({ transaction, collection }) => {
249 const deletedKey = transaction.mutations[0].key
250 await api.deleteTodo(deletedKey)
252```
253​
254```ts
255// Delete handler with refetch (Query Collection)
256onDelete: async ({ transaction, collection }) => {
257 const keysToDelete = transaction.mutations.map(m => m.key)
258 await api.deleteTodos(keysToDelete)
259 // Trigger refetch to sync server state
260 await collection.utils.refetch()
262```
263​
264```ts
265// Delete handler with sync wait (Electric Collection)
266onDelete: async ({ transaction, collection }) => {
267 const mutation = transaction.mutations[0]
268 const result = await api.deleteTodo(mutation.original.id)
269 // Wait for txid to sync
270 await collection.utils.awaitTxId(result.txid)
272```
273​
274```ts
275// Delete handler with confirmation
276onDelete: async ({ transaction, collection }) => {
277 const mutation = transaction.mutations[0]
278 const shouldDelete = await confirmDeletion(mutation.original)
279 if (!shouldDelete) {
280 throw new Error('Delete cancelled by user')
281 }
282 await api.deleteTodo(mutation.original.id)
284```
285​
286```ts
287// Delete handler with optimistic rollback
288onDelete: async ({ transaction, collection }) => {
289 const mutation = transaction.mutations[0]
290 try {
291 await api.deleteTodo(mutation.original.id)
292 } catch (error) {
293 // Transaction will automatically rollback optimistic changes
294 console.error('Delete failed, rolling back:', error)
295 throw error
296 }
298```
299​
300#### Inherited from
301​
302[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onDelete`](BaseCollectionConfig.md#ondelete)
303​
304***
305​
306### onInsert?
307​
308```ts
309optional onInsert: InsertMutationFn<T, TKey, TUtils>;
310```
311​
312Defined in: [packages/db/src/types.ts:1021](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1021)
313​
314Optional asynchronous handler function called before an insert operation
315​
316#### Examples
317​
318```ts
319// Basic insert handler
320onInsert: async ({ transaction, collection }) => {
321 const newItem = transaction.mutations[0].modified
322 await api.createTodo(newItem)
324```
325​
326```ts
327// Insert handler with refetch (Query Collection)
328onInsert: async ({ transaction, collection }) => {
329 const newItem = transaction.mutations[0].modified
330 await api.createTodo(newItem)
331 // Trigger refetch to sync server state
332 await collection.utils.refetch()
334```
335​
336```ts
337// Insert handler with sync wait (Electric Collection)
338onInsert: async ({ transaction, collection }) => {
339 const newItem = transaction.mutations[0].modified
340 const result = await api.createTodo(newItem)
341 // Wait for txid to sync
342 await collection.utils.awaitTxId(result.txid)
344```
345​
346```ts
347// Insert handler with multiple items
348onInsert: async ({ transaction, collection }) => {
349 const items = transaction.mutations.map(m => m.modified)
350 await api.createTodos(items)
351 // Refetch to get updated data from server
352 await collection.utils.refetch()
354```
355​
356```ts
357// Insert handler with error handling
358onInsert: async ({ transaction, collection }) => {
359 try {
360 const newItem = transaction.mutations[0].modified
361 await api.createTodo(newItem)
362 } catch (error) {
363 console.error('Insert failed:', error)
364 throw error // This will cause the transaction to rollback
365 }
367```
368​
369#### Inherited from
370​
371[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onInsert`](BaseCollectionConfig.md#oninsert)
372​
373***
374​
375### onUpdate?
376​
377```ts
378optional onUpdate: UpdateMutationFn<T, TKey, TUtils>;
379```
380​
381Defined in: [packages/db/src/types.ts:1076](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1076)
382​
383Optional asynchronous handler function called before an update operation
384​
385#### Examples
386​
387```ts
388// Basic update handler
389onUpdate: async ({ transaction, collection }) => {
390 const updatedItem = transaction.mutations[0].modified
391 await api.updateTodo(updatedItem.id, updatedItem)
393```
394​
395```ts
396// Update handler with refetch (Query Collection)
397onUpdate: async ({ transaction, collection }) => {
398 const mutation = transaction.mutations[0]
399 const changes = mutation.changes // Only the changed fields
400 await api.updateTodo(mutation.original.id, changes)
401 // Trigger refetch to sync server state
402 await collection.utils.refetch()
404```
405​
406```ts
407// Update handler with sync wait (Electric Collection)
408onUpdate: async ({ transaction, collection }) => {
409 const mutation = transaction.mutations[0]
410 const result = await api.updateTodo(mutation.original.id, mutation.changes)
411 // Wait for txid to sync
412 await collection.utils.awaitTxId(result.txid)
414```
415​
416```ts
417// Update handler with multiple items
418onUpdate: async ({ transaction, collection }) => {
419 const updates = transaction.mutations.map(m => ({
420 id: m.key,
421 changes: m.changes
422 }))
423 await api.updateTodos(updates)
424 await collection.utils.refetch()
426```
427​
428```ts
429// Update handler with optimistic rollback
430onUpdate: async ({ transaction, collection }) => {
431 const mutation = transaction.mutations[0]
432 try {
433 await api.updateTodo(mutation.original.id, mutation.changes)
434 } catch (error) {
435 // Transaction will automatically rollback optimistic changes
436 console.error('Update failed, rolling back:', error)
437 throw error
438 }
440```
441​
442#### Inherited from
443​
444[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onUpdate`](BaseCollectionConfig.md#onupdate)
445​
446***
447​
448### schema?
449​
450```ts
451optional schema: TSchema;
452```
453​
454Defined in: [packages/db/src/types.ts:888](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L888)
455​
456#### Inherited from
457​
458[`BaseCollectionConfig`](BaseCollectionConfig.md).[`schema`](BaseCollectionConfig.md#schema)
459​
460***
461​
462### startSync?
463​
464```ts
465optional startSync: boolean;
466```
467​
468Defined in: [packages/db/src/types.ts:927](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L927)
469​
470Whether to eagerly start syncing on collection creation.
471When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches.
472​
473Note: Even with startSync=true, collections will pause syncing when there are no active
474subscribers (typically when components querying the collection unmount), resuming when new
475subscribers attach. This preserves normal staleTime/gcTime behavior.
476​
477#### Default
478​
479```ts
480false
481```
482​
483#### Inherited from
484​
485[`BaseCollectionConfig`](BaseCollectionConfig.md).[`startSync`](BaseCollectionConfig.md#startsync)
486​
487***
488​
489### sync
490​
491```ts
492sync: SyncConfig<T, TKey>;
493```
494​
495Defined in: [packages/db/src/types.ts:1148](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1148)
496​
497***
498​
499### syncMode?
500​
501```ts
502optional syncMode: SyncMode;
503```
504​
505Defined in: [packages/db/src/types.ts:971](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L971)
506​
507The mode of sync to use for the collection.
508​
509#### Default
510​
511`eager`
512​
513#### Description
514​
515- `eager`: syncs all data immediately on preload
516- `on-demand`: syncs data in incremental snapshots when the collection is queried
517The exact implementation of the sync mode is up to the sync implementation.
518​
519#### Inherited from
520​
521[`BaseCollectionConfig`](BaseCollectionConfig.md).[`syncMode`](BaseCollectionConfig.md#syncmode)
522​
523***
524​
525### utils?
526​
527```ts
528optional utils: TUtils;
529```
530​
531Defined in: [packages/db/src/types.ts:1139](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1139)
532​
533#### Inherited from
534​
535[`BaseCollectionConfig`](BaseCollectionConfig.md).[`utils`](BaseCollectionConfig.md#utils)