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

BaseCollectionConfig.md

454 lines9.6 KB

1---
2id: BaseCollectionConfig
3title: BaseCollectionConfig
4---
5​
6Defined in: [packages/db/src/types.ts:613](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L613)
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:667](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L667)
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:692](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L692)
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:681](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L681)
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:838](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L838)
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:646](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L646)
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:637](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L637)
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:626](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L626)
199​
200***
201​
202### onDelete?
203​
204```ts
205optional onDelete: DeleteMutationFn<T, TKey, TUtils, TReturn>;
206```
207​
208Defined in: [packages/db/src/types.ts:830](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L830)
209​
210Optional asynchronous handler function called before a delete operation
211​
212#### Param
213​
214Object containing transaction and collection information
215​
216#### Returns
217​
218Promise resolving to any value
219​
220#### Examples
221​
222```ts
223// Basic delete handler
224onDelete: async ({ transaction, collection }) => {
225 const deletedKey = transaction.mutations[0].key
226 await api.deleteTodo(deletedKey)
228```
229​
230```ts
231// Delete handler with multiple items
232onDelete: async ({ transaction, collection }) => {
233 const keysToDelete = transaction.mutations.map(m => m.key)
234 await api.deleteTodos(keysToDelete)
236```
237​
238```ts
239// Delete handler with confirmation
240onDelete: async ({ transaction, collection }) => {
241 const mutation = transaction.mutations[0]
242 const shouldDelete = await confirmDeletion(mutation.original)
243 if (!shouldDelete) {
244 throw new Error('Delete cancelled by user')
245 }
246 await api.deleteTodo(mutation.original.id)
248```
249​
250```ts
251// Delete handler with optimistic rollback
252onDelete: async ({ transaction, collection }) => {
253 const mutation = transaction.mutations[0]
254 try {
255 await api.deleteTodo(mutation.original.id)
256 } catch (error) {
257 // Transaction will automatically rollback optimistic changes
258 console.error('Delete failed, rolling back:', error)
259 throw error
260 }
262```
263​
264***
265​
266### onInsert?
267​
268```ts
269optional onInsert: InsertMutationFn<T, TKey, TUtils, TReturn>;
270```
271​
272Defined in: [packages/db/src/types.ts:743](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L743)
273​
274Optional asynchronous handler function called before an insert operation
275​
276#### Param
277​
278Object containing transaction and collection information
279​
280#### Returns
281​
282Promise resolving to any value
283​
284#### Examples
285​
286```ts
287// Basic insert handler
288onInsert: async ({ transaction, collection }) => {
289 const newItem = transaction.mutations[0].modified
290 await api.createTodo(newItem)
292```
293​
294```ts
295// Insert handler with multiple items
296onInsert: async ({ transaction, collection }) => {
297 const items = transaction.mutations.map(m => m.modified)
298 await api.createTodos(items)
300```
301​
302```ts
303// Insert handler with error handling
304onInsert: async ({ transaction, collection }) => {
305 try {
306 const newItem = transaction.mutations[0].modified
307 const result = await api.createTodo(newItem)
308 return result
309 } catch (error) {
310 console.error('Insert failed:', error)
311 throw error // This will cause the transaction to fail
312 }
314```
315​
316```ts
317// Insert handler with metadata
318onInsert: async ({ transaction, collection }) => {
319 const mutation = transaction.mutations[0]
320 await api.createTodo(mutation.modified, {
321 source: mutation.metadata?.source,
322 timestamp: mutation.createdAt
323 })
325```
326​
327***
328​
329### onUpdate?
330​
331```ts
332optional onUpdate: UpdateMutationFn<T, TKey, TUtils, TReturn>;
333```
334​
335Defined in: [packages/db/src/types.ts:787](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L787)
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***
392​
393### schema?
394​
395```ts
396optional schema: TSchema;
397```
398​
399Defined in: [packages/db/src/types.ts:627](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L627)
400​
401***
402​
403### startSync?
404​
405```ts
406optional startSync: boolean;
407```
408​
409Defined in: [packages/db/src/types.ts:657](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L657)
410​
411Whether to eagerly start syncing on collection creation.
412When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches.
413​
414Note: Even with startSync=true, collections will pause syncing when there are no active
415subscribers (typically when components querying the collection unmount), resuming when new
416subscribers attach. This preserves normal staleTime/gcTime behavior.
417​
418#### Default
419​
420```ts
421false
422```
423​
424***
425​
426### syncMode?
427​
428```ts
429optional syncMode: SyncMode;
430```
431​
432Defined in: [packages/db/src/types.ts:701](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L701)
433​
434The mode of sync to use for the collection.
435​
436#### Default
437​
438`eager`
439​
440#### Description
441​
442- `eager`: syncs all data immediately on preload
443- `on-demand`: syncs data in incremental snapshots when the collection is queried
444The exact implementation of the sync mode is up to the sync implementation.
445​
446***
447​
448### utils?
449​
450```ts
451optional utils: TUtils;
452```
453​
454Defined in: [packages/db/src/types.ts:840](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L840)