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

BaseCollectionConfig.md

452 lines9.4 KB

1---
2id: BaseCollectionConfig
3title: BaseCollectionConfig
4---
5​
6# Interface: BaseCollectionConfig\<T, TKey, TSchema, TUtils, TReturn\>
7​
8Defined in: [packages/db/src/types.ts:521](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L521)
9​
10## Extended by
11​
12- [`CollectionConfig`](CollectionConfig.md)
13- [`LocalStorageCollectionConfig`](LocalStorageCollectionConfig.md)
14​
15## Type Parameters
16​
17### T
18​
19`T` *extends* `object` = `Record`\<`string`, `unknown`\>
20​
21### TKey
22​
23`TKey` *extends* `string` \| `number` = `string` \| `number`
24​
25### TSchema
26​
27`TSchema` *extends* `StandardSchemaV1` = `never`
28​
29### TUtils
30​
31`TUtils` *extends* [`UtilsRecord`](../type-aliases/UtilsRecord.md) = [`UtilsRecord`](../type-aliases/UtilsRecord.md)
32​
33### TReturn
34​
35`TReturn` = `any`
36​
37## Properties
38​
39### autoIndex?
40​
41```ts
42optional autoIndex: "off" | "eager";
43```
44​
45Defined in: [packages/db/src/types.ts:571](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L571)
46​
47Auto-indexing mode for the collection.
48When enabled, indexes will be automatically created for simple where expressions.
49​
50#### Default
51​
52```ts
53"off"
54```
55​
56#### Description
57​
58- "off": No automatic indexing (default). Use explicit indexes for better bundle size.
59- "eager": Automatically create indexes for simple where expressions in subscribeChanges.
60 Requires setting defaultIndexType.
61​
62***
63​
64### compare()?
65​
66```ts
67optional compare: (x, y) => number;
68```
69​
70Defined in: [packages/db/src/types.ts:596](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L596)
71​
72Optional function to compare two items.
73This is used to order the items in the collection.
74​
75#### Parameters
76​
77##### x
78​
79`T`
80​
81The first item to compare
82​
83##### y
84​
85`T`
86​
87The second item to compare
88​
89#### Returns
90​
91`number`
92​
93A number indicating the order of the items
94​
95#### Example
96​
97```ts
98// For a collection with a 'createdAt' field
99compare: (x, y) => x.createdAt.getTime() - y.createdAt.getTime()
100```
101​
102***
103​
104### defaultIndexType?
105​
106```ts
107optional defaultIndexType: IndexConstructor<TKey>;
108```
109​
110Defined in: [packages/db/src/types.ts:585](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L585)
111​
112Default index type to use when creating indexes without an explicit type.
113Required for auto-indexing. Import from '@tanstack/db'.
114​
115#### Example
116​
117```ts
118import { BasicIndex } from '@tanstack/db'
119const collection = createCollection({
120 defaultIndexType: BasicIndex,
121 autoIndex: 'eager',
122 // ...
123})
124```
125​
126***
127​
128### defaultStringCollation?
129​
130```ts
131optional defaultStringCollation: StringCollationConfig;
132```
133​
134Defined in: [packages/db/src/types.ts:742](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L742)
135​
136Specifies how to compare data in the collection.
137This should be configured to match data ordering on the backend.
138E.g., when using the Electric DB collection these options
139 should match the database's collation settings.
140​
141***
142​
143### gcTime?
144​
145```ts
146optional gcTime: number;
147```
148​
149Defined in: [packages/db/src/types.ts:550](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L550)
150​
151Time in milliseconds after which the collection will be garbage collected
152when it has no active subscribers. Defaults to 5 minutes (300000ms).
153​
154***
155​
156### getKey()
157​
158```ts
159getKey: (item) => TKey;
160```
161​
162Defined in: [packages/db/src/types.ts:545](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L545)
163​
164Function to extract the ID from an object
165This is required for update/delete operations which now only accept IDs
166​
167#### Parameters
168​
169##### item
170​
171`T`
172​
173The item to extract the ID from
174​
175#### Returns
176​
177`TKey`
178​
179The ID string for the item
180​
181#### Example
182​
183```ts
184// For a collection with a 'uuid' field as the primary key
185getKey: (item) => item.uuid
186```
187​
188***
189​
190### id?
191​
192```ts
193optional id: string;
194```
195​
196Defined in: [packages/db/src/types.ts:534](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L534)
197​
198***
199​
200### onDelete?
201​
202```ts
203optional onDelete: DeleteMutationFn<T, TKey, TUtils, TReturn>;
204```
205​
206Defined in: [packages/db/src/types.ts:734](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L734)
207​
208Optional asynchronous handler function called before a delete operation
209​
210#### Param
211​
212Object containing transaction and collection information
213​
214#### Returns
215​
216Promise resolving to any value
217​
218#### Examples
219​
220```ts
221// Basic delete handler
222onDelete: async ({ transaction, collection }) => {
223 const deletedKey = transaction.mutations[0].key
224 await api.deleteTodo(deletedKey)
226```
227​
228```ts
229// Delete handler with multiple items
230onDelete: async ({ transaction, collection }) => {
231 const keysToDelete = transaction.mutations.map(m => m.key)
232 await api.deleteTodos(keysToDelete)
234```
235​
236```ts
237// Delete handler with confirmation
238onDelete: async ({ transaction, collection }) => {
239 const mutation = transaction.mutations[0]
240 const shouldDelete = await confirmDeletion(mutation.original)
241 if (!shouldDelete) {
242 throw new Error('Delete cancelled by user')
243 }
244 await api.deleteTodo(mutation.original.id)
246```
247​
248```ts
249// Delete handler with optimistic rollback
250onDelete: async ({ transaction, collection }) => {
251 const mutation = transaction.mutations[0]
252 try {
253 await api.deleteTodo(mutation.original.id)
254 } catch (error) {
255 // Transaction will automatically rollback optimistic changes
256 console.error('Delete failed, rolling back:', error)
257 throw error
258 }
260```
261​
262***
263​
264### onInsert?
265​
266```ts
267optional onInsert: InsertMutationFn<T, TKey, TUtils, TReturn>;
268```
269​
270Defined in: [packages/db/src/types.ts:647](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L647)
271​
272Optional asynchronous handler function called before an insert operation
273​
274#### Param
275​
276Object containing transaction and collection information
277​
278#### Returns
279​
280Promise resolving to any value
281​
282#### Examples
283​
284```ts
285// Basic insert handler
286onInsert: async ({ transaction, collection }) => {
287 const newItem = transaction.mutations[0].modified
288 await api.createTodo(newItem)
290```
291​
292```ts
293// Insert handler with multiple items
294onInsert: async ({ transaction, collection }) => {
295 const items = transaction.mutations.map(m => m.modified)
296 await api.createTodos(items)
298```
299​
300```ts
301// Insert handler with error handling
302onInsert: async ({ transaction, collection }) => {
303 try {
304 const newItem = transaction.mutations[0].modified
305 const result = await api.createTodo(newItem)
306 return result
307 } catch (error) {
308 console.error('Insert failed:', error)
309 throw error // This will cause the transaction to fail
310 }
312```
313​
314```ts
315// Insert handler with metadata
316onInsert: async ({ transaction, collection }) => {
317 const mutation = transaction.mutations[0]
318 await api.createTodo(mutation.modified, {
319 source: mutation.metadata?.source,
320 timestamp: mutation.createdAt
321 })
323```
324​
325***
326​
327### onUpdate?
328​
329```ts
330optional onUpdate: UpdateMutationFn<T, TKey, TUtils, TReturn>;
331```
332​
333Defined in: [packages/db/src/types.ts:691](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L691)
334​
335Optional asynchronous handler function called before an update operation
336​
337#### Param
338​
339Object containing transaction and collection information
340​
341#### Returns
342​
343Promise resolving to any value
344​
345#### Examples
346​
347```ts
348// Basic update handler
349onUpdate: async ({ transaction, collection }) => {
350 const updatedItem = transaction.mutations[0].modified
351 await api.updateTodo(updatedItem.id, updatedItem)
353```
354​
355```ts
356// Update handler with partial updates
357onUpdate: async ({ transaction, collection }) => {
358 const mutation = transaction.mutations[0]
359 const changes = mutation.changes // Only the changed fields
360 await api.updateTodo(mutation.original.id, changes)
362```
363​
364```ts
365// Update handler with multiple items
366onUpdate: async ({ transaction, collection }) => {
367 const updates = transaction.mutations.map(m => ({
368 id: m.key,
369 changes: m.changes
370 }))
371 await api.updateTodos(updates)
373```
374​
375```ts
376// Update handler with optimistic rollback
377onUpdate: async ({ transaction, collection }) => {
378 const mutation = transaction.mutations[0]
379 try {
380 await api.updateTodo(mutation.original.id, mutation.changes)
381 } catch (error) {
382 // Transaction will automatically rollback optimistic changes
383 console.error('Update failed, rolling back:', error)
384 throw error
385 }
387```
388​
389***
390​
391### schema?
392​
393```ts
394optional schema: TSchema;
395```
396​
397Defined in: [packages/db/src/types.ts:535](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L535)
398​
399***
400​
401### startSync?
402​
403```ts
404optional startSync: boolean;
405```
406​
407Defined in: [packages/db/src/types.ts:561](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L561)
408​
409Whether to eagerly start syncing on collection creation.
410When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches.
411​
412Note: Even with startSync=true, collections will pause syncing when there are no active
413subscribers (typically when components querying the collection unmount), resuming when new
414subscribers attach. This preserves normal staleTime/gcTime behavior.
415​
416#### Default
417​
418```ts
419false
420```
421​
422***
423​
424### syncMode?
425​
426```ts
427optional syncMode: SyncMode;
428```
429​
430Defined in: [packages/db/src/types.ts:605](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L605)
431​
432The mode of sync to use for the collection.
433​
434#### Default
435​
436`eager`
437​
438#### Description
439​
440- `eager`: syncs all data immediately on preload
441- `on-demand`: syncs data in incremental snapshots when the collection is queried
442The exact implementation of the sync mode is up to the sync implementation.
443​
444***
445​
446### utils?
447​
448```ts
449optional utils: TUtils;
450```
451​
452Defined in: [packages/db/src/types.ts:744](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L744)