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

BaseCollectionConfig.md

427 lines8.9 KB

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