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

CollectionConfig.md

543 lines12.9 KB

1---
2id: CollectionConfig
3title: CollectionConfig
4---
5​
6Defined in: [packages/db/src/types.ts:998](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L998)
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:773](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L773)
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:798](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L798)
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:787](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L787)
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:993](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L993)
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:752](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L752)
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:743](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L743)
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:732](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L732)
218​
219#### Inherited from
220​
221[`BaseCollectionConfig`](BaseCollectionConfig.md).[`id`](BaseCollectionConfig.md#id)
222​
223***
224​
225### onDelete?
226​
227```ts
228optional onDelete:
229 | DeleteMutationFn<T, TKey, TUtils, void>
230| DeleteMutationFn<T, TKey, TUtils, any>;
231```
232​
233Defined in: [packages/db/src/types.ts:982](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L982)
234​
235Optional asynchronous handler function called before a delete operation
236Returning a value is deprecated; coordinate synchronization through collection utilities instead.
237​
238#### Examples
239​
240```ts
241// Basic delete handler
242onDelete: async ({ transaction, collection }) => {
243 const deletedKey = transaction.mutations[0].key
244 await api.deleteTodo(deletedKey)
246```
247​
248```ts
249// Delete handler with refetch (Query Collection)
250onDelete: async ({ transaction, collection }) => {
251 const keysToDelete = transaction.mutations.map(m => m.key)
252 await api.deleteTodos(keysToDelete)
253 // Trigger refetch to sync server state
254 await collection.utils.refetch()
255 // Prevent the pre-1.0 compatibility wrapper from refetching again.
256 return { refetch: false }
258```
259​
260```ts
261// Delete handler with sync wait (Electric Collection)
262onDelete: async ({ transaction, collection }) => {
263 const mutation = transaction.mutations[0]
264 const result = await api.deleteTodo(mutation.original.id)
265 // Wait for txid to sync
266 await collection.utils.awaitTxId(result.txid)
268```
269​
270```ts
271// Delete handler with confirmation
272onDelete: async ({ transaction, collection }) => {
273 const mutation = transaction.mutations[0]
274 const shouldDelete = await confirmDeletion(mutation.original)
275 if (!shouldDelete) {
276 throw new Error('Delete cancelled by user')
277 }
278 await api.deleteTodo(mutation.original.id)
280```
281​
282```ts
283// Delete handler with optimistic rollback
284onDelete: async ({ transaction, collection }) => {
285 const mutation = transaction.mutations[0]
286 try {
287 await api.deleteTodo(mutation.original.id)
288 } catch (error) {
289 // Transaction will automatically rollback optimistic changes
290 console.error('Delete failed, rolling back:', error)
291 throw error
292 }
294```
295​
296#### Inherited from
297​
298[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onDelete`](BaseCollectionConfig.md#ondelete)
299​
300***
301​
302### onInsert?
303​
304```ts
305optional onInsert:
306 | InsertMutationFn<T, TKey, TUtils, void>
307| InsertMutationFn<T, TKey, TUtils, any>;
308```
309​
310Defined in: [packages/db/src/types.ts:861](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L861)
311​
312Optional asynchronous handler function called before an insert operation
313Returning a value is deprecated; coordinate synchronization through collection utilities instead.
314​
315#### Examples
316​
317```ts
318// Basic insert handler
319onInsert: async ({ transaction, collection }) => {
320 const newItem = transaction.mutations[0].modified
321 await api.createTodo(newItem)
323```
324​
325```ts
326// Insert handler with refetch (Query Collection)
327onInsert: async ({ transaction, collection }) => {
328 const newItem = transaction.mutations[0].modified
329 await api.createTodo(newItem)
330 // Trigger refetch to sync server state
331 await collection.utils.refetch()
332 // Prevent the pre-1.0 compatibility wrapper from refetching again.
333 return { refetch: false }
335```
336​
337```ts
338// Insert handler with sync wait (Electric Collection)
339onInsert: async ({ transaction, collection }) => {
340 const newItem = transaction.mutations[0].modified
341 const result = await api.createTodo(newItem)
342 // Wait for txid to sync
343 await collection.utils.awaitTxId(result.txid)
345```
346​
347```ts
348// Insert handler with multiple items
349onInsert: async ({ transaction, collection }) => {
350 const items = transaction.mutations.map(m => m.modified)
351 await api.createTodos(items)
352 // Refetch to get updated data from server
353 await collection.utils.refetch()
354 return { refetch: false }
356```
357​
358```ts
359// Insert handler with error handling
360onInsert: async ({ transaction, collection }) => {
361 try {
362 const newItem = transaction.mutations[0].modified
363 await api.createTodo(newItem)
364 } catch (error) {
365 console.error('Insert failed:', error)
366 throw error // This will cause the transaction to rollback
367 }
369```
370​
371#### Inherited from
372​
373[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onInsert`](BaseCollectionConfig.md#oninsert)
374​
375***
376​
377### onUpdate?
378​
379```ts
380optional onUpdate:
381 | UpdateMutationFn<T, TKey, TUtils, void>
382| UpdateMutationFn<T, TKey, TUtils, any>;
383```
384​
385Defined in: [packages/db/src/types.ts:923](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L923)
386​
387Optional asynchronous handler function called before an update operation
388Returning a value is deprecated; coordinate synchronization through collection utilities instead.
389​
390#### Examples
391​
392```ts
393// Basic update handler
394onUpdate: async ({ transaction, collection }) => {
395 const updatedItem = transaction.mutations[0].modified
396 await api.updateTodo(updatedItem.id, updatedItem)
398```
399​
400```ts
401// Update handler with refetch (Query Collection)
402onUpdate: async ({ transaction, collection }) => {
403 const mutation = transaction.mutations[0]
404 const changes = mutation.changes // Only the changed fields
405 await api.updateTodo(mutation.original.id, changes)
406 // Trigger refetch to sync server state
407 await collection.utils.refetch()
408 // Prevent the pre-1.0 compatibility wrapper from refetching again.
409 return { refetch: false }
411```
412​
413```ts
414// Update handler with sync wait (Electric Collection)
415onUpdate: async ({ transaction, collection }) => {
416 const mutation = transaction.mutations[0]
417 const result = await api.updateTodo(mutation.original.id, mutation.changes)
418 // Wait for txid to sync
419 await collection.utils.awaitTxId(result.txid)
421```
422​
423```ts
424// Update handler with multiple items
425onUpdate: async ({ transaction, collection }) => {
426 const updates = transaction.mutations.map(m => ({
427 id: m.key,
428 changes: m.changes
429 }))
430 await api.updateTodos(updates)
431 await collection.utils.refetch()
432 return { refetch: false }
434```
435​
436```ts
437// Update handler with optimistic rollback
438onUpdate: async ({ transaction, collection }) => {
439 const mutation = transaction.mutations[0]
440 try {
441 await api.updateTodo(mutation.original.id, mutation.changes)
442 } catch (error) {
443 // Transaction will automatically rollback optimistic changes
444 console.error('Update failed, rolling back:', error)
445 throw error
446 }
448```
449​
450#### Inherited from
451​
452[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onUpdate`](BaseCollectionConfig.md#onupdate)
453​
454***
455​
456### schema?
457​
458```ts
459optional schema: TSchema;
460```
461​
462Defined in: [packages/db/src/types.ts:733](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L733)
463​
464#### Inherited from
465​
466[`BaseCollectionConfig`](BaseCollectionConfig.md).[`schema`](BaseCollectionConfig.md#schema)
467​
468***
469​
470### startSync?
471​
472```ts
473optional startSync: boolean;
474```
475​
476Defined in: [packages/db/src/types.ts:763](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L763)
477​
478Whether to eagerly start syncing on collection creation.
479When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches.
480​
481Note: Even with startSync=true, collections will pause syncing when there are no active
482subscribers (typically when components querying the collection unmount), resuming when new
483subscribers attach. This preserves normal staleTime/gcTime behavior.
484​
485#### Default
486​
487```ts
488false
489```
490​
491#### Inherited from
492​
493[`BaseCollectionConfig`](BaseCollectionConfig.md).[`startSync`](BaseCollectionConfig.md#startsync)
494​
495***
496​
497### sync
498​
499```ts
500sync: SyncConfig<T, TKey>;
501```
502​
503Defined in: [packages/db/src/types.ts:1004](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1004)
504​
505***
506​
507### syncMode?
508​
509```ts
510optional syncMode: SyncMode;
511```
512​
513Defined in: [packages/db/src/types.ts:807](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L807)
514​
515The mode of sync to use for the collection.
516​
517#### Default
518​
519`eager`
520​
521#### Description
522​
523- `eager`: syncs all data immediately on preload
524- `on-demand`: syncs data in incremental snapshots when the collection is queried
525The exact implementation of the sync mode is up to the sync implementation.
526​
527#### Inherited from
528​
529[`BaseCollectionConfig`](BaseCollectionConfig.md).[`syncMode`](BaseCollectionConfig.md#syncmode)
530​
531***
532​
533### utils?
534​
535```ts
536optional utils: TUtils;
537```
538​
539Defined in: [packages/db/src/types.ts:995](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L995)
540​
541#### Inherited from
542​
543[`BaseCollectionConfig`](BaseCollectionConfig.md).[`utils`](BaseCollectionConfig.md#utils)