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

BaseCollectionConfig.md

471 lines11.0 KB

1---
2id: BaseCollectionConfig
3title: BaseCollectionConfig
4---
5​
6Defined in: [packages/db/src/types.ts:875](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L875)
7​
8## Extended by
9​
10- [`CollectionConfig`](CollectionConfig.md)
11- [`LocalStorageCollectionConfig`](LocalStorageCollectionConfig.md)
12- [`IndexedDBCollectionConfig`](IndexedDBCollectionConfig.md)
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: "eager" | "off";
38```
39​
40Defined in: [packages/db/src/types.ts:937](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L937)
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"off"
49```
50​
51#### Description
52​
53- "off": No automatic indexing (default). Use explicit indexes for better bundle size.
54- "eager": Automatically create indexes for simple where expressions in subscribeChanges.
55 Requires setting defaultIndexType.
56​
57***
58​
59### compare()?
60​
61```ts
62optional compare: (x, y) => number;
63```
64​
65Defined in: [packages/db/src/types.ts:962](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L962)
66​
67Optional function to compare two items.
68This is used to order the items in the collection.
69​
70#### Parameters
71​
72##### x
73​
74`T`
75​
76The first item to compare
77​
78##### y
79​
80`T`
81​
82The second item to compare
83​
84#### Returns
85​
86`number`
87​
88A number indicating the order of the items
89​
90#### Example
91​
92```ts
93// For a collection with a 'createdAt' field
94compare: (x, y) => x.createdAt.getTime() - y.createdAt.getTime()
95```
96​
97***
98​
99### defaultIndexType?
100​
101```ts
102optional defaultIndexType: IndexConstructor<TKey>;
103```
104​
105Defined in: [packages/db/src/types.ts:951](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L951)
106​
107Default index type to use when creating indexes without an explicit type.
108Required for auto-indexing. Import from '@tanstack/db'.
109​
110#### Example
111​
112```ts
113import { BasicIndex } from '@tanstack/db'
114const collection = createCollection({
115 defaultIndexType: BasicIndex,
116 autoIndex: 'eager',
117 // ...
118})
119```
120​
121***
122​
123### defaultStringCollation?
124​
125```ts
126optional defaultStringCollation: StringCollationConfig;
127```
128​
129Defined in: [packages/db/src/types.ts:1137](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1137)
130​
131Specifies how to compare data in the collection.
132This should be configured to match data ordering on the backend.
133E.g., when using the Electric DB collection these options
134 should match the database's collation settings.
135​
136***
137​
138### gcTime?
139​
140```ts
141optional gcTime: number;
142```
143​
144Defined in: [packages/db/src/types.ts:916](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L916)
145​
146Time in milliseconds after which the collection will be garbage collected
147when it has no active subscribers. Defaults to 5 minutes (300000ms).
148Sync started without subscribers gets a minimum 50ms handoff grace period
149until a subscriber attaches. After the last subscriber leaves, gcTime
150applies without that startup minimum.
151Pending preloads retain the collection until they settle. Preloading ready
152data refreshes the retention period. A persisting transaction that touches
153the collection also retains it, and the period starts again when the last
154one completes or fails, preserving any remaining startup grace. Pending
155manual transactions do not retain it; keep a subscription for draft
156visibility until commit or rollback. Rolling
157back a manual transaction that stayed pending preserves the existing GC
158deadline. Cleanup runs at a host idle opportunity after the delay.
159A non-positive or non-finite value
160disables automatic garbage collection.
161​
162***
163​
164### getKey()
165​
166```ts
167getKey: (item) => TKey;
168```
169​
170Defined in: [packages/db/src/types.ts:898](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L898)
171​
172Function to extract the ID from an object
173This is required for update/delete operations which now only accept IDs
174​
175#### Parameters
176​
177##### item
178​
179`T`
180​
181The item to extract the ID from
182​
183#### Returns
184​
185`TKey`
186​
187The ID string for the item
188​
189#### Example
190​
191```ts
192// For a collection with a 'uuid' field as the primary key
193getKey: (item) => item.uuid
194```
195​
196***
197​
198### id?
199​
200```ts
201optional id: string;
202```
203​
204Defined in: [packages/db/src/types.ts:887](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L887)
205​
206***
207​
208### onDelete?
209​
210```ts
211optional onDelete: DeleteMutationFn<T, TKey, TUtils>;
212```
213​
214Defined in: [packages/db/src/types.ts:1129](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1129)
215​
216Optional asynchronous handler function called before a delete operation
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 refetch (Query Collection)
230onDelete: async ({ transaction, collection }) => {
231 const keysToDelete = transaction.mutations.map(m => m.key)
232 await api.deleteTodos(keysToDelete)
233 // Trigger refetch to sync server state
234 await collection.utils.refetch()
236```
237​
238```ts
239// Delete handler with sync wait (Electric Collection)
240onDelete: async ({ transaction, collection }) => {
241 const mutation = transaction.mutations[0]
242 const result = await api.deleteTodo(mutation.original.id)
243 // Wait for txid to sync
244 await collection.utils.awaitTxId(result.txid)
246```
247​
248```ts
249// Delete handler with confirmation
250onDelete: async ({ transaction, collection }) => {
251 const mutation = transaction.mutations[0]
252 const shouldDelete = await confirmDeletion(mutation.original)
253 if (!shouldDelete) {
254 throw new Error('Delete cancelled by user')
255 }
256 await api.deleteTodo(mutation.original.id)
258```
259​
260```ts
261// Delete handler with optimistic rollback
262onDelete: async ({ transaction, collection }) => {
263 const mutation = transaction.mutations[0]
264 try {
265 await api.deleteTodo(mutation.original.id)
266 } catch (error) {
267 // Transaction will automatically rollback optimistic changes
268 console.error('Delete failed, rolling back:', error)
269 throw error
270 }
272```
273​
274***
275​
276### onInsert?
277​
278```ts
279optional onInsert: InsertMutationFn<T, TKey, TUtils>;
280```
281​
282Defined in: [packages/db/src/types.ts:1021](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1021)
283​
284Optional asynchronous handler function called before an insert operation
285​
286#### Examples
287​
288```ts
289// Basic insert handler
290onInsert: async ({ transaction, collection }) => {
291 const newItem = transaction.mutations[0].modified
292 await api.createTodo(newItem)
294```
295​
296```ts
297// Insert handler with refetch (Query Collection)
298onInsert: async ({ transaction, collection }) => {
299 const newItem = transaction.mutations[0].modified
300 await api.createTodo(newItem)
301 // Trigger refetch to sync server state
302 await collection.utils.refetch()
304```
305​
306```ts
307// Insert handler with sync wait (Electric Collection)
308onInsert: async ({ transaction, collection }) => {
309 const newItem = transaction.mutations[0].modified
310 const result = await api.createTodo(newItem)
311 // Wait for txid to sync
312 await collection.utils.awaitTxId(result.txid)
314```
315​
316```ts
317// Insert handler with multiple items
318onInsert: async ({ transaction, collection }) => {
319 const items = transaction.mutations.map(m => m.modified)
320 await api.createTodos(items)
321 // Refetch to get updated data from server
322 await collection.utils.refetch()
324```
325​
326```ts
327// Insert handler with error handling
328onInsert: async ({ transaction, collection }) => {
329 try {
330 const newItem = transaction.mutations[0].modified
331 await api.createTodo(newItem)
332 } catch (error) {
333 console.error('Insert failed:', error)
334 throw error // This will cause the transaction to rollback
335 }
337```
338​
339***
340​
341### onUpdate?
342​
343```ts
344optional onUpdate: UpdateMutationFn<T, TKey, TUtils>;
345```
346​
347Defined in: [packages/db/src/types.ts:1076](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1076)
348​
349Optional asynchronous handler function called before an update operation
350​
351#### Examples
352​
353```ts
354// Basic update handler
355onUpdate: async ({ transaction, collection }) => {
356 const updatedItem = transaction.mutations[0].modified
357 await api.updateTodo(updatedItem.id, updatedItem)
359```
360​
361```ts
362// Update handler with refetch (Query Collection)
363onUpdate: async ({ transaction, collection }) => {
364 const mutation = transaction.mutations[0]
365 const changes = mutation.changes // Only the changed fields
366 await api.updateTodo(mutation.original.id, changes)
367 // Trigger refetch to sync server state
368 await collection.utils.refetch()
370```
371​
372```ts
373// Update handler with sync wait (Electric Collection)
374onUpdate: async ({ transaction, collection }) => {
375 const mutation = transaction.mutations[0]
376 const result = await api.updateTodo(mutation.original.id, mutation.changes)
377 // Wait for txid to sync
378 await collection.utils.awaitTxId(result.txid)
380```
381​
382```ts
383// Update handler with multiple items
384onUpdate: async ({ transaction, collection }) => {
385 const updates = transaction.mutations.map(m => ({
386 id: m.key,
387 changes: m.changes
388 }))
389 await api.updateTodos(updates)
390 await collection.utils.refetch()
392```
393​
394```ts
395// Update handler with optimistic rollback
396onUpdate: async ({ transaction, collection }) => {
397 const mutation = transaction.mutations[0]
398 try {
399 await api.updateTodo(mutation.original.id, mutation.changes)
400 } catch (error) {
401 // Transaction will automatically rollback optimistic changes
402 console.error('Update failed, rolling back:', error)
403 throw error
404 }
406```
407​
408***
409​
410### schema?
411​
412```ts
413optional schema: TSchema;
414```
415​
416Defined in: [packages/db/src/types.ts:888](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L888)
417​
418***
419​
420### startSync?
421​
422```ts
423optional startSync: boolean;
424```
425​
426Defined in: [packages/db/src/types.ts:927](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L927)
427​
428Whether to eagerly start syncing on collection creation.
429When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches.
430​
431Note: Even with startSync=true, collections will pause syncing when there are no active
432subscribers (typically when components querying the collection unmount), resuming when new
433subscribers attach. This preserves normal staleTime/gcTime behavior.
434​
435#### Default
436​
437```ts
438false
439```
440​
441***
442​
443### syncMode?
444​
445```ts
446optional syncMode: SyncMode;
447```
448​
449Defined in: [packages/db/src/types.ts:971](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L971)
450​
451The mode of sync to use for the collection.
452​
453#### Default
454​
455`eager`
456​
457#### Description
458​
459- `eager`: syncs all data immediately on preload
460- `on-demand`: syncs data in incremental snapshots when the collection is queried
461The exact implementation of the sync mode is up to the sync implementation.
462​
463***
464​
465### utils?
466​
467```ts
468optional utils: TUtils;
469```
470​
471Defined in: [packages/db/src/types.ts:1139](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1139)