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

CollectionConfig.md

484 lines10.4 KB

1---
2id: CollectionConfig
3title: CollectionConfig
4---
5​
6# Interface: CollectionConfig\<T, TKey, TSchema, TUtils\>
7​
8Defined in: [packages/db/src/types.ts:710](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L710)
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:548](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L548)
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"eager"
49```
50​
51#### Description
52​
53- "off": No automatic indexing
54- "eager": Automatically create indexes for simple where expressions in subscribeChanges (default)
55​
56#### Inherited from
57​
58[`BaseCollectionConfig`](BaseCollectionConfig.md).[`autoIndex`](BaseCollectionConfig.md#autoindex)
59​
60***
61​
62### compare()?
63​
64```ts
65optional compare: (x, y) => number;
66```
67​
68Defined in: [packages/db/src/types.ts:559](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L559)
69​
70Optional function to compare two items.
71This is used to order the items in the collection.
72​
73#### Parameters
74​
75##### x
76​
77`T`
78​
79The first item to compare
80​
81##### y
82​
83`T`
84​
85The second item to compare
86​
87#### Returns
88​
89`number`
90​
91A number indicating the order of the items
92​
93#### Example
94​
95```ts
96// For a collection with a 'createdAt' field
97compare: (x, y) => x.createdAt.getTime() - y.createdAt.getTime()
98```
99​
100#### Inherited from
101​
102[`BaseCollectionConfig`](BaseCollectionConfig.md).[`compare`](BaseCollectionConfig.md#compare)
103​
104***
105​
106### defaultStringCollation?
107​
108```ts
109optional defaultStringCollation: StringCollationConfig;
110```
111​
112Defined in: [packages/db/src/types.ts:705](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L705)
113​
114Specifies how to compare data in the collection.
115This should be configured to match data ordering on the backend.
116E.g., when using the Electric DB collection these options
117 should match the database's collation settings.
118​
119#### Inherited from
120​
121[`BaseCollectionConfig`](BaseCollectionConfig.md).[`defaultStringCollation`](BaseCollectionConfig.md#defaultstringcollation)
122​
123***
124​
125### gcTime?
126​
127```ts
128optional gcTime: number;
129```
130​
131Defined in: [packages/db/src/types.ts:528](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L528)
132​
133Time in milliseconds after which the collection will be garbage collected
134when it has no active subscribers. Defaults to 5 minutes (300000ms).
135​
136#### Inherited from
137​
138[`BaseCollectionConfig`](BaseCollectionConfig.md).[`gcTime`](BaseCollectionConfig.md#gctime)
139​
140***
141​
142### getKey()
143​
144```ts
145getKey: (item) => TKey;
146```
147​
148Defined in: [packages/db/src/types.ts:523](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L523)
149​
150Function to extract the ID from an object
151This is required for update/delete operations which now only accept IDs
152​
153#### Parameters
154​
155##### item
156​
157`T`
158​
159The item to extract the ID from
160​
161#### Returns
162​
163`TKey`
164​
165The ID string for the item
166​
167#### Example
168​
169```ts
170// For a collection with a 'uuid' field as the primary key
171getKey: (item) => item.uuid
172```
173​
174#### Inherited from
175​
176[`BaseCollectionConfig`](BaseCollectionConfig.md).[`getKey`](BaseCollectionConfig.md#getkey)
177​
178***
179​
180### id?
181​
182```ts
183optional id: string;
184```
185​
186Defined in: [packages/db/src/types.ts:512](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L512)
187​
188#### Inherited from
189​
190[`BaseCollectionConfig`](BaseCollectionConfig.md).[`id`](BaseCollectionConfig.md#id)
191​
192***
193​
194### onDelete?
195​
196```ts
197optional onDelete: DeleteMutationFn<T, TKey, TUtils, any>;
198```
199​
200Defined in: [packages/db/src/types.ts:697](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L697)
201​
202Optional asynchronous handler function called before a delete operation
203​
204#### Param
205​
206Object containing transaction and collection information
207​
208#### Returns
209​
210Promise resolving to any value
211​
212#### Examples
213​
214```ts
215// Basic delete handler
216onDelete: async ({ transaction, collection }) => {
217 const deletedKey = transaction.mutations[0].key
218 await api.deleteTodo(deletedKey)
220```
221​
222```ts
223// Delete handler with multiple items
224onDelete: async ({ transaction, collection }) => {
225 const keysToDelete = transaction.mutations.map(m => m.key)
226 await api.deleteTodos(keysToDelete)
228```
229​
230```ts
231// Delete handler with confirmation
232onDelete: async ({ transaction, collection }) => {
233 const mutation = transaction.mutations[0]
234 const shouldDelete = await confirmDeletion(mutation.original)
235 if (!shouldDelete) {
236 throw new Error('Delete cancelled by user')
237 }
238 await api.deleteTodo(mutation.original.id)
240```
241​
242```ts
243// Delete handler with optimistic rollback
244onDelete: async ({ transaction, collection }) => {
245 const mutation = transaction.mutations[0]
246 try {
247 await api.deleteTodo(mutation.original.id)
248 } catch (error) {
249 // Transaction will automatically rollback optimistic changes
250 console.error('Delete failed, rolling back:', error)
251 throw error
252 }
254```
255​
256#### Inherited from
257​
258[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onDelete`](BaseCollectionConfig.md#ondelete)
259​
260***
261​
262### onInsert?
263​
264```ts
265optional onInsert: InsertMutationFn<T, TKey, TUtils, any>;
266```
267​
268Defined in: [packages/db/src/types.ts:610](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L610)
269​
270Optional asynchronous handler function called before an insert operation
271​
272#### Param
273​
274Object containing transaction and collection information
275​
276#### Returns
277​
278Promise resolving to any value
279​
280#### Examples
281​
282```ts
283// Basic insert handler
284onInsert: async ({ transaction, collection }) => {
285 const newItem = transaction.mutations[0].modified
286 await api.createTodo(newItem)
288```
289​
290```ts
291// Insert handler with multiple items
292onInsert: async ({ transaction, collection }) => {
293 const items = transaction.mutations.map(m => m.modified)
294 await api.createTodos(items)
296```
297​
298```ts
299// Insert handler with error handling
300onInsert: async ({ transaction, collection }) => {
301 try {
302 const newItem = transaction.mutations[0].modified
303 const result = await api.createTodo(newItem)
304 return result
305 } catch (error) {
306 console.error('Insert failed:', error)
307 throw error // This will cause the transaction to fail
308 }
310```
311​
312```ts
313// Insert handler with metadata
314onInsert: async ({ transaction, collection }) => {
315 const mutation = transaction.mutations[0]
316 await api.createTodo(mutation.modified, {
317 source: mutation.metadata?.source,
318 timestamp: mutation.createdAt
319 })
321```
322​
323#### Inherited from
324​
325[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onInsert`](BaseCollectionConfig.md#oninsert)
326​
327***
328​
329### onUpdate?
330​
331```ts
332optional onUpdate: UpdateMutationFn<T, TKey, TUtils, any>;
333```
334​
335Defined in: [packages/db/src/types.ts:654](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L654)
336​
337Optional asynchronous handler function called before an update operation
338​
339#### Param
340​
341Object containing transaction and collection information
342​
343#### Returns
344​
345Promise resolving to any value
346​
347#### Examples
348​
349```ts
350// Basic update handler
351onUpdate: async ({ transaction, collection }) => {
352 const updatedItem = transaction.mutations[0].modified
353 await api.updateTodo(updatedItem.id, updatedItem)
355```
356​
357```ts
358// Update handler with partial updates
359onUpdate: async ({ transaction, collection }) => {
360 const mutation = transaction.mutations[0]
361 const changes = mutation.changes // Only the changed fields
362 await api.updateTodo(mutation.original.id, changes)
364```
365​
366```ts
367// Update handler with multiple items
368onUpdate: async ({ transaction, collection }) => {
369 const updates = transaction.mutations.map(m => ({
370 id: m.key,
371 changes: m.changes
372 }))
373 await api.updateTodos(updates)
375```
376​
377```ts
378// Update handler with optimistic rollback
379onUpdate: async ({ transaction, collection }) => {
380 const mutation = transaction.mutations[0]
381 try {
382 await api.updateTodo(mutation.original.id, mutation.changes)
383 } catch (error) {
384 // Transaction will automatically rollback optimistic changes
385 console.error('Update failed, rolling back:', error)
386 throw error
387 }
389```
390​
391#### Inherited from
392​
393[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onUpdate`](BaseCollectionConfig.md#onupdate)
394​
395***
396​
397### schema?
398​
399```ts
400optional schema: TSchema;
401```
402​
403Defined in: [packages/db/src/types.ts:513](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L513)
404​
405#### Inherited from
406​
407[`BaseCollectionConfig`](BaseCollectionConfig.md).[`schema`](BaseCollectionConfig.md#schema)
408​
409***
410​
411### startSync?
412​
413```ts
414optional startSync: boolean;
415```
416​
417Defined in: [packages/db/src/types.ts:539](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L539)
418​
419Whether to eagerly start syncing on collection creation.
420When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches.
421​
422Note: Even with startSync=true, collections will pause syncing when there are no active
423subscribers (typically when components querying the collection unmount), resuming when new
424subscribers attach. This preserves normal staleTime/gcTime behavior.
425​
426#### Default
427​
428```ts
429false
430```
431​
432#### Inherited from
433​
434[`BaseCollectionConfig`](BaseCollectionConfig.md).[`startSync`](BaseCollectionConfig.md#startsync)
435​
436***
437​
438### sync
439​
440```ts
441sync: SyncConfig<T, TKey>;
442```
443​
444Defined in: [packages/db/src/types.ts:716](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L716)
445​
446***
447​
448### syncMode?
449​
450```ts
451optional syncMode: SyncMode;
452```
453​
454Defined in: [packages/db/src/types.ts:568](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L568)
455​
456The mode of sync to use for the collection.
457​
458#### Default
459​
460`eager`
461​
462#### Description
463​
464- `eager`: syncs all data immediately on preload
465- `on-demand`: syncs data in incremental snapshots when the collection is queried
466The exact implementation of the sync mode is up to the sync implementation.
467​
468#### Inherited from
469​
470[`BaseCollectionConfig`](BaseCollectionConfig.md).[`syncMode`](BaseCollectionConfig.md#syncmode)
471​
472***
473​
474### utils?
475​
476```ts
477optional utils: TUtils;
478```
479​
480Defined in: [packages/db/src/types.ts:707](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L707)
481​
482#### Inherited from
483​
484[`BaseCollectionConfig`](BaseCollectionConfig.md).[`utils`](BaseCollectionConfig.md#utils)