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

BaseCollectionConfig.md

482 lines11.2 KB

1---
2id: BaseCollectionConfig
3title: BaseCollectionConfig
4---
5​
6Defined in: [packages/db/src/types.ts:718](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L718)
7​
8## Extended by
9​
10- [`CollectionConfig`](CollectionConfig.md)
11- [`LocalStorageCollectionConfig`](LocalStorageCollectionConfig.md)
12​
13## Type Parameters
14​
15### T
16​
17`T` *extends* `object` = `Record`\<`string`, `unknown`\>
18​
19### TKey
20​
21`TKey` *extends* `string` \| `number` = `string` \| `number`
22​
23### TSchema
24​
25`TSchema` *extends* `StandardSchemaV1` = `never`
26​
27### TUtils
28​
29`TUtils` *extends* [`UtilsRecord`](../type-aliases/UtilsRecord.md) = [`UtilsRecord`](../type-aliases/UtilsRecord.md)
30​
31### TReturn
32​
33`TReturn` = `any`
34​
35## Properties
36​
37### autoIndex?
38​
39```ts
40optional autoIndex: "off" | "eager";
41```
42​
43Defined in: [packages/db/src/types.ts:772](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L772)
44​
45Auto-indexing mode for the collection.
46When enabled, indexes will be automatically created for simple where expressions.
47​
48#### Default
49​
50```ts
51"off"
52```
53​
54#### Description
55​
56- "off": No automatic indexing (default). Use explicit indexes for better bundle size.
57- "eager": Automatically create indexes for simple where expressions in subscribeChanges.
58 Requires setting defaultIndexType.
59​
60***
61​
62### compare()?
63​
64```ts
65optional compare: (x, y) => number;
66```
67​
68Defined in: [packages/db/src/types.ts:797](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L797)
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***
101​
102### defaultIndexType?
103​
104```ts
105optional defaultIndexType: IndexConstructor<TKey>;
106```
107​
108Defined in: [packages/db/src/types.ts:786](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L786)
109​
110Default index type to use when creating indexes without an explicit type.
111Required for auto-indexing. Import from '@tanstack/db'.
112​
113#### Example
114​
115```ts
116import { BasicIndex } from '@tanstack/db'
117const collection = createCollection({
118 defaultIndexType: BasicIndex,
119 autoIndex: 'eager',
120 // ...
121})
122```
123​
124***
125​
126### defaultStringCollation?
127​
128```ts
129optional defaultStringCollation: StringCollationConfig;
130```
131​
132Defined in: [packages/db/src/types.ts:992](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L992)
133​
134Specifies how to compare data in the collection.
135This should be configured to match data ordering on the backend.
136E.g., when using the Electric DB collection these options
137 should match the database's collation settings.
138​
139***
140​
141### gcTime?
142​
143```ts
144optional gcTime: number;
145```
146​
147Defined in: [packages/db/src/types.ts:751](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L751)
148​
149Time in milliseconds after which the collection will be garbage collected
150when it has no active subscribers. Defaults to 5 minutes (300000ms).
151Sync started without subscribers gets a minimum 50ms grace period.
152Pending preloads retain the collection until they settle. Preloading ready
153data refreshes the retention period. A non-positive or non-finite value
154disables automatic garbage collection.
155​
156***
157​
158### getKey()
159​
160```ts
161getKey: (item) => TKey;
162```
163​
164Defined in: [packages/db/src/types.ts:742](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L742)
165​
166Function to extract the ID from an object
167This is required for update/delete operations which now only accept IDs
168​
169#### Parameters
170​
171##### item
172​
173`T`
174​
175The item to extract the ID from
176​
177#### Returns
178​
179`TKey`
180​
181The ID string for the item
182​
183#### Example
184​
185```ts
186// For a collection with a 'uuid' field as the primary key
187getKey: (item) => item.uuid
188```
189​
190***
191​
192### id?
193​
194```ts
195optional id: string;
196```
197​
198Defined in: [packages/db/src/types.ts:731](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L731)
199​
200***
201​
202### onDelete?
203​
204```ts
205optional onDelete:
206 | DeleteMutationFn<T, TKey, TUtils, void>
207| DeleteMutationFn<T, TKey, TUtils, TReturn>;
208```
209​
210Defined in: [packages/db/src/types.ts:981](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L981)
211​
212Optional asynchronous handler function called before a delete operation
213Returning a value is deprecated; coordinate synchronization through collection utilities instead.
214​
215#### Examples
216​
217```ts
218// Basic delete handler
219onDelete: async ({ transaction, collection }) => {
220 const deletedKey = transaction.mutations[0].key
221 await api.deleteTodo(deletedKey)
223```
224​
225```ts
226// Delete handler with refetch (Query Collection)
227onDelete: async ({ transaction, collection }) => {
228 const keysToDelete = transaction.mutations.map(m => m.key)
229 await api.deleteTodos(keysToDelete)
230 // Trigger refetch to sync server state
231 await collection.utils.refetch()
232 // Prevent the pre-1.0 compatibility wrapper from refetching again.
233 return { refetch: false }
235```
236​
237```ts
238// Delete handler with sync wait (Electric Collection)
239onDelete: async ({ transaction, collection }) => {
240 const mutation = transaction.mutations[0]
241 const result = await api.deleteTodo(mutation.original.id)
242 // Wait for txid to sync
243 await collection.utils.awaitTxId(result.txid)
245```
246​
247```ts
248// Delete handler with confirmation
249onDelete: async ({ transaction, collection }) => {
250 const mutation = transaction.mutations[0]
251 const shouldDelete = await confirmDeletion(mutation.original)
252 if (!shouldDelete) {
253 throw new Error('Delete cancelled by user')
254 }
255 await api.deleteTodo(mutation.original.id)
257```
258​
259```ts
260// Delete handler with optimistic rollback
261onDelete: async ({ transaction, collection }) => {
262 const mutation = transaction.mutations[0]
263 try {
264 await api.deleteTodo(mutation.original.id)
265 } catch (error) {
266 // Transaction will automatically rollback optimistic changes
267 console.error('Delete failed, rolling back:', error)
268 throw error
269 }
271```
272​
273***
274​
275### onInsert?
276​
277```ts
278optional onInsert:
279 | InsertMutationFn<T, TKey, TUtils, void>
280| InsertMutationFn<T, TKey, TUtils, TReturn>;
281```
282​
283Defined in: [packages/db/src/types.ts:860](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L860)
284​
285Optional asynchronous handler function called before an insert operation
286Returning a value is deprecated; coordinate synchronization through collection utilities instead.
287​
288#### Examples
289​
290```ts
291// Basic insert handler
292onInsert: async ({ transaction, collection }) => {
293 const newItem = transaction.mutations[0].modified
294 await api.createTodo(newItem)
296```
297​
298```ts
299// Insert handler with refetch (Query Collection)
300onInsert: async ({ transaction, collection }) => {
301 const newItem = transaction.mutations[0].modified
302 await api.createTodo(newItem)
303 // Trigger refetch to sync server state
304 await collection.utils.refetch()
305 // Prevent the pre-1.0 compatibility wrapper from refetching again.
306 return { refetch: false }
308```
309​
310```ts
311// Insert handler with sync wait (Electric Collection)
312onInsert: async ({ transaction, collection }) => {
313 const newItem = transaction.mutations[0].modified
314 const result = await api.createTodo(newItem)
315 // Wait for txid to sync
316 await collection.utils.awaitTxId(result.txid)
318```
319​
320```ts
321// Insert handler with multiple items
322onInsert: async ({ transaction, collection }) => {
323 const items = transaction.mutations.map(m => m.modified)
324 await api.createTodos(items)
325 // Refetch to get updated data from server
326 await collection.utils.refetch()
327 return { refetch: false }
329```
330​
331```ts
332// Insert handler with error handling
333onInsert: async ({ transaction, collection }) => {
334 try {
335 const newItem = transaction.mutations[0].modified
336 await api.createTodo(newItem)
337 } catch (error) {
338 console.error('Insert failed:', error)
339 throw error // This will cause the transaction to rollback
340 }
342```
343​
344***
345​
346### onUpdate?
347​
348```ts
349optional onUpdate:
350 | UpdateMutationFn<T, TKey, TUtils, void>
351| UpdateMutationFn<T, TKey, TUtils, TReturn>;
352```
353​
354Defined in: [packages/db/src/types.ts:922](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L922)
355​
356Optional asynchronous handler function called before an update operation
357Returning a value is deprecated; coordinate synchronization through collection utilities instead.
358​
359#### Examples
360​
361```ts
362// Basic update handler
363onUpdate: async ({ transaction, collection }) => {
364 const updatedItem = transaction.mutations[0].modified
365 await api.updateTodo(updatedItem.id, updatedItem)
367```
368​
369```ts
370// Update handler with refetch (Query Collection)
371onUpdate: async ({ transaction, collection }) => {
372 const mutation = transaction.mutations[0]
373 const changes = mutation.changes // Only the changed fields
374 await api.updateTodo(mutation.original.id, changes)
375 // Trigger refetch to sync server state
376 await collection.utils.refetch()
377 // Prevent the pre-1.0 compatibility wrapper from refetching again.
378 return { refetch: false }
380```
381​
382```ts
383// Update handler with sync wait (Electric Collection)
384onUpdate: async ({ transaction, collection }) => {
385 const mutation = transaction.mutations[0]
386 const result = await api.updateTodo(mutation.original.id, mutation.changes)
387 // Wait for txid to sync
388 await collection.utils.awaitTxId(result.txid)
390```
391​
392```ts
393// Update handler with multiple items
394onUpdate: async ({ transaction, collection }) => {
395 const updates = transaction.mutations.map(m => ({
396 id: m.key,
397 changes: m.changes
398 }))
399 await api.updateTodos(updates)
400 await collection.utils.refetch()
401 return { refetch: false }
403```
404​
405```ts
406// Update handler with optimistic rollback
407onUpdate: async ({ transaction, collection }) => {
408 const mutation = transaction.mutations[0]
409 try {
410 await api.updateTodo(mutation.original.id, mutation.changes)
411 } catch (error) {
412 // Transaction will automatically rollback optimistic changes
413 console.error('Update failed, rolling back:', error)
414 throw error
415 }
417```
418​
419***
420​
421### schema?
422​
423```ts
424optional schema: TSchema;
425```
426​
427Defined in: [packages/db/src/types.ts:732](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L732)
428​
429***
430​
431### startSync?
432​
433```ts
434optional startSync: boolean;
435```
436​
437Defined in: [packages/db/src/types.ts:762](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L762)
438​
439Whether to eagerly start syncing on collection creation.
440When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches.
441​
442Note: Even with startSync=true, collections will pause syncing when there are no active
443subscribers (typically when components querying the collection unmount), resuming when new
444subscribers attach. This preserves normal staleTime/gcTime behavior.
445​
446#### Default
447​
448```ts
449false
450```
451​
452***
453​
454### syncMode?
455​
456```ts
457optional syncMode: SyncMode;
458```
459​
460Defined in: [packages/db/src/types.ts:806](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L806)
461​
462The mode of sync to use for the collection.
463​
464#### Default
465​
466`eager`
467​
468#### Description
469​
470- `eager`: syncs all data immediately on preload
471- `on-demand`: syncs data in incremental snapshots when the collection is queried
472The exact implementation of the sync mode is up to the sync implementation.
473​
474***
475​
476### utils?
477​
478```ts
479optional utils: TUtils;
480```
481​
482Defined in: [packages/db/src/types.ts:994](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L994)