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

collectionconfig.md

365 lines7.5 KB

1---
2id: CollectionConfig
3title: CollectionConfig
4---
5​
6<!-- DO NOT EDIT: this page is autogenerated from the type comments -->
7​
8# Interface: CollectionConfig\<T, TKey, TSchema, TInsertInput\>
9​
10Defined in: [packages/db/src/types.ts:349](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L349)
11​
12## Type Parameters
13​
14• **T** *extends* `object` = `Record`\<`string`, `unknown`\>
15​
16• **TKey** *extends* `string` \| `number` = `string` \| `number`
17​
18• **TSchema** *extends* `StandardSchemaV1` = `StandardSchemaV1`
19​
20• **TInsertInput** *extends* `object` = `T`
21​
22## Properties
23​
24### autoIndex?
25​
26```ts
27optional autoIndex: "off" | "eager";
28```
29​
30Defined in: [packages/db/src/types.ts:388](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L388)
31​
32Auto-indexing mode for the collection.
33When enabled, indexes will be automatically created for simple where expressions.
34​
35#### Default
36​
37```ts
38"eager"
39```
40​
41#### Description
42​
43- "off": No automatic indexing
44- "eager": Automatically create indexes for simple where expressions in subscribeChanges (default)
45​
46***
47​
48### compare()?
49​
50```ts
51optional compare: (x, y) => number;
52```
53​
54Defined in: [packages/db/src/types.ts:399](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L399)
55​
56Optional function to compare two items.
57This is used to order the items in the collection.
58​
59#### Parameters
60​
61##### x
62​
63`T`
64​
65The first item to compare
66​
67##### y
68​
69`T`
70​
71The second item to compare
72​
73#### Returns
74​
75`number`
76​
77A number indicating the order of the items
78​
79#### Example
80​
81```ts
82// For a collection with a 'createdAt' field
83compare: (x, y) => x.createdAt.getTime() - y.createdAt.getTime()
84```
85​
86***
87​
88### gcTime?
89​
90```ts
91optional gcTime: number;
92```
93​
94Defined in: [packages/db/src/types.ts:374](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L374)
95​
96Time in milliseconds after which the collection will be garbage collected
97when it has no active subscribers. Defaults to 5 minutes (300000ms).
98​
99***
100​
101### getKey()
102​
103```ts
104getKey: (item) => TKey;
105```
106​
107Defined in: [packages/db/src/types.ts:369](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L369)
108​
109Function to extract the ID from an object
110This is required for update/delete operations which now only accept IDs
111​
112#### Parameters
113​
114##### item
115​
116`T`
117​
118The item to extract the ID from
119​
120#### Returns
121​
122`TKey`
123​
124The ID string for the item
125​
126#### Example
127​
128```ts
129// For a collection with a 'uuid' field as the primary key
130getKey: (item) => item.uuid
131```
132​
133***
134​
135### id?
136​
137```ts
138optional id: string;
139```
140​
141Defined in: [packages/db/src/types.ts:357](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L357)
142​
143***
144​
145### onDelete?
146​
147```ts
148optional onDelete: DeleteMutationFn<T, TKey, Record<string, Fn>>;
149```
150​
151Defined in: [packages/db/src/types.ts:528](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L528)
152​
153Optional asynchronous handler function called before a delete operation
154​
155#### Param
156​
157Object containing transaction and collection information
158​
159#### Returns
160​
161Promise resolving to any value
162​
163#### Examples
164​
165```ts
166// Basic delete handler
167onDelete: async ({ transaction, collection }) => {
168 const deletedKey = transaction.mutations[0].key
169 await api.deleteTodo(deletedKey)
171```
172​
173```ts
174// Delete handler with multiple items
175onDelete: async ({ transaction, collection }) => {
176 const keysToDelete = transaction.mutations.map(m => m.key)
177 await api.deleteTodos(keysToDelete)
179```
180​
181```ts
182// Delete handler with confirmation
183onDelete: async ({ transaction, collection }) => {
184 const mutation = transaction.mutations[0]
185 const shouldDelete = await confirmDeletion(mutation.original)
186 if (!shouldDelete) {
187 throw new Error('Delete cancelled by user')
188 }
189 await api.deleteTodo(mutation.original.id)
191```
192​
193```ts
194// Delete handler with optimistic rollback
195onDelete: async ({ transaction, collection }) => {
196 const mutation = transaction.mutations[0]
197 try {
198 await api.deleteTodo(mutation.original.id)
199 } catch (error) {
200 // Transaction will automatically rollback optimistic changes
201 console.error('Delete failed, rolling back:', error)
202 throw error
203 }
205```
206​
207***
208​
209### onInsert?
210​
211```ts
212optional onInsert: InsertMutationFn<TInsertInput, TKey, Record<string, Fn>>;
213```
214​
215Defined in: [packages/db/src/types.ts:441](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L441)
216​
217Optional asynchronous handler function called before an insert operation
218​
219#### Param
220​
221Object containing transaction and collection information
222​
223#### Returns
224​
225Promise resolving to any value
226​
227#### Examples
228​
229```ts
230// Basic insert handler
231onInsert: async ({ transaction, collection }) => {
232 const newItem = transaction.mutations[0].modified
233 await api.createTodo(newItem)
235```
236​
237```ts
238// Insert handler with multiple items
239onInsert: async ({ transaction, collection }) => {
240 const items = transaction.mutations.map(m => m.modified)
241 await api.createTodos(items)
243```
244​
245```ts
246// Insert handler with error handling
247onInsert: async ({ transaction, collection }) => {
248 try {
249 const newItem = transaction.mutations[0].modified
250 const result = await api.createTodo(newItem)
251 return result
252 } catch (error) {
253 console.error('Insert failed:', error)
254 throw error // This will cause the transaction to fail
255 }
257```
258​
259```ts
260// Insert handler with metadata
261onInsert: async ({ transaction, collection }) => {
262 const mutation = transaction.mutations[0]
263 await api.createTodo(mutation.modified, {
264 source: mutation.metadata?.source,
265 timestamp: mutation.createdAt
266 })
268```
269​
270***
271​
272### onUpdate?
273​
274```ts
275optional onUpdate: UpdateMutationFn<T, TKey, Record<string, Fn>>;
276```
277​
278Defined in: [packages/db/src/types.ts:485](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L485)
279​
280Optional asynchronous handler function called before an update operation
281​
282#### Param
283​
284Object containing transaction and collection information
285​
286#### Returns
287​
288Promise resolving to any value
289​
290#### Examples
291​
292```ts
293// Basic update handler
294onUpdate: async ({ transaction, collection }) => {
295 const updatedItem = transaction.mutations[0].modified
296 await api.updateTodo(updatedItem.id, updatedItem)
298```
299​
300```ts
301// Update handler with partial updates
302onUpdate: async ({ transaction, collection }) => {
303 const mutation = transaction.mutations[0]
304 const changes = mutation.changes // Only the changed fields
305 await api.updateTodo(mutation.original.id, changes)
307```
308​
309```ts
310// Update handler with multiple items
311onUpdate: async ({ transaction, collection }) => {
312 const updates = transaction.mutations.map(m => ({
313 id: m.key,
314 changes: m.changes
315 }))
316 await api.updateTodos(updates)
318```
319​
320```ts
321// Update handler with optimistic rollback
322onUpdate: async ({ transaction, collection }) => {
323 const mutation = transaction.mutations[0]
324 try {
325 await api.updateTodo(mutation.original.id, mutation.changes)
326 } catch (error) {
327 // Transaction will automatically rollback optimistic changes
328 console.error('Update failed, rolling back:', error)
329 throw error
330 }
332```
333​
334***
335​
336### schema?
337​
338```ts
339optional schema: TSchema;
340```
341​
342Defined in: [packages/db/src/types.ts:359](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L359)
343​
344***
345​
346### startSync?
347​
348```ts
349optional startSync: boolean;
350```
351​
352Defined in: [packages/db/src/types.ts:379](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L379)
353​
354Whether to start syncing immediately when the collection is created.
355Defaults to false for lazy loading. Set to true to immediately sync.
356​
357***
358​
359### sync
360​
361```ts
362sync: SyncConfig<T, TKey>;
363```
364​
365Defined in: [packages/db/src/types.ts:358](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L358)