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

LocalOnlyCollectionConfig.md

504 lines10.5 KB

1---
2id: LocalOnlyCollectionConfig
3title: LocalOnlyCollectionConfig
4---
5​
6Defined in: [packages/db/src/local-only.ts:24](https://github.com/TanStack/db/blob/main/packages/db/src/local-only.ts#L24)
7​
8Configuration interface for Local-only collection options
9​
10## Extends
11​
12- `Omit`\<[`BaseCollectionConfig`](BaseCollectionConfig.md)\<`T`, `TKey`, `TSchema`, [`LocalOnlyCollectionUtils`](LocalOnlyCollectionUtils.md)\>, `"gcTime"` \| `"startSync"`\>
13​
14## Type Parameters
15​
16### T
17​
18`T` *extends* `object` = `object`
19​
20The type of items in the collection
21​
22### TSchema
23​
24`TSchema` *extends* `StandardSchemaV1` = `never`
25​
26The schema type for validation
27​
28### TKey
29​
30`TKey` *extends* `string` \| `number` = `string` \| `number`
31​
32The type of the key returned by `getKey`
33​
34## Properties
35​
36### autoIndex?
37​
38```ts
39optional autoIndex: "eager" | "off";
40```
41​
42Defined in: [packages/db/src/types.ts:937](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L937)
43​
44Auto-indexing mode for the collection.
45When enabled, indexes will be automatically created for simple where expressions.
46​
47#### Default
48​
49```ts
50"off"
51```
52​
53#### Description
54​
55- "off": No automatic indexing (default). Use explicit indexes for better bundle size.
56- "eager": Automatically create indexes for simple where expressions in subscribeChanges.
57 Requires setting defaultIndexType.
58​
59#### Inherited from
60​
61[`BaseCollectionConfig`](BaseCollectionConfig.md).[`autoIndex`](BaseCollectionConfig.md#autoindex)
62​
63***
64​
65### compare()?
66​
67```ts
68optional compare: (x, y) => number;
69```
70​
71Defined in: [packages/db/src/types.ts:962](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L962)
72​
73Optional function to compare two items.
74This is used to order the items in the collection.
75​
76#### Parameters
77​
78##### x
79​
80`T`
81​
82The first item to compare
83​
84##### y
85​
86`T`
87​
88The second item to compare
89​
90#### Returns
91​
92`number`
93​
94A number indicating the order of the items
95​
96#### Example
97​
98```ts
99// For a collection with a 'createdAt' field
100compare: (x, y) => x.createdAt.getTime() - y.createdAt.getTime()
101```
102​
103#### Inherited from
104​
105```ts
106Omit.compare
107```
108​
109***
110​
111### defaultIndexType?
112​
113```ts
114optional defaultIndexType: IndexConstructor<TKey>;
115```
116​
117Defined in: [packages/db/src/types.ts:951](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L951)
118​
119Default index type to use when creating indexes without an explicit type.
120Required for auto-indexing. Import from '@tanstack/db'.
121​
122#### Example
123​
124```ts
125import { BasicIndex } from '@tanstack/db'
126const collection = createCollection({
127 defaultIndexType: BasicIndex,
128 autoIndex: 'eager',
129 // ...
130})
131```
132​
133#### Inherited from
134​
135```ts
136Omit.defaultIndexType
137```
138​
139***
140​
141### defaultStringCollation?
142​
143```ts
144optional defaultStringCollation: StringCollationConfig;
145```
146​
147Defined in: [packages/db/src/types.ts:1137](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1137)
148​
149Specifies how to compare data in the collection.
150This should be configured to match data ordering on the backend.
151E.g., when using the Electric DB collection these options
152 should match the database's collation settings.
153​
154#### Inherited from
155​
156```ts
157Omit.defaultStringCollation
158```
159​
160***
161​
162### getKey()
163​
164```ts
165getKey: (item) => TKey;
166```
167​
168Defined in: [packages/db/src/types.ts:898](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L898)
169​
170Function to extract the ID from an object
171This is required for update/delete operations which now only accept IDs
172​
173#### Parameters
174​
175##### item
176​
177`T`
178​
179The item to extract the ID from
180​
181#### Returns
182​
183`TKey`
184​
185The ID string for the item
186​
187#### Example
188​
189```ts
190// For a collection with a 'uuid' field as the primary key
191getKey: (item) => item.uuid
192```
193​
194#### Inherited from
195​
196```ts
197Omit.getKey
198```
199​
200***
201​
202### id?
203​
204```ts
205optional id: string;
206```
207​
208Defined in: [packages/db/src/types.ts:887](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L887)
209​
210#### Inherited from
211​
212[`BaseCollectionConfig`](BaseCollectionConfig.md).[`id`](BaseCollectionConfig.md#id)
213​
214***
215​
216### initialData?
217​
218```ts
219optional initialData: T[];
220```
221​
222Defined in: [packages/db/src/local-only.ts:37](https://github.com/TanStack/db/blob/main/packages/db/src/local-only.ts#L37)
223​
224Optional initial data to populate the collection with on creation.
225It loads when the Collection starts empty: at creation, or after
226cleanup. `reload()` keeps the rows, including the user's writes.
227​
228***
229​
230### onDelete?
231​
232```ts
233optional onDelete: DeleteMutationFn<T, TKey, LocalOnlyCollectionUtils>;
234```
235​
236Defined in: [packages/db/src/types.ts:1129](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1129)
237​
238Optional asynchronous handler function called before a delete operation
239​
240#### Examples
241​
242```ts
243// Basic delete handler
244onDelete: async ({ transaction, collection }) => {
245 const deletedKey = transaction.mutations[0].key
246 await api.deleteTodo(deletedKey)
248```
249​
250```ts
251// Delete handler with refetch (Query Collection)
252onDelete: async ({ transaction, collection }) => {
253 const keysToDelete = transaction.mutations.map(m => m.key)
254 await api.deleteTodos(keysToDelete)
255 // Trigger refetch to sync server state
256 await collection.utils.refetch()
258```
259​
260```ts
261// Delete handler with sync wait (Electric Collection)
262onDelete: async ({ transaction, collection }) => {
263 const mutation = transaction.mutations[0]
264 const result = await api.deleteTodo(mutation.original.id)
265 // Wait for txid to sync
266 await collection.utils.awaitTxId(result.txid)
268```
269​
270```ts
271// Delete handler with confirmation
272onDelete: async ({ transaction, collection }) => {
273 const mutation = transaction.mutations[0]
274 const shouldDelete = await confirmDeletion(mutation.original)
275 if (!shouldDelete) {
276 throw new Error('Delete cancelled by user')
277 }
278 await api.deleteTodo(mutation.original.id)
280```
281​
282```ts
283// Delete handler with optimistic rollback
284onDelete: async ({ transaction, collection }) => {
285 const mutation = transaction.mutations[0]
286 try {
287 await api.deleteTodo(mutation.original.id)
288 } catch (error) {
289 // Transaction will automatically rollback optimistic changes
290 console.error('Delete failed, rolling back:', error)
291 throw error
292 }
294```
295​
296#### Inherited from
297​
298```ts
299Omit.onDelete
300```
301​
302***
303​
304### onInsert?
305​
306```ts
307optional onInsert: InsertMutationFn<T, TKey, LocalOnlyCollectionUtils>;
308```
309​
310Defined in: [packages/db/src/types.ts:1021](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1021)
311​
312Optional asynchronous handler function called before an insert operation
313​
314#### Examples
315​
316```ts
317// Basic insert handler
318onInsert: async ({ transaction, collection }) => {
319 const newItem = transaction.mutations[0].modified
320 await api.createTodo(newItem)
322```
323​
324```ts
325// Insert handler with refetch (Query Collection)
326onInsert: async ({ transaction, collection }) => {
327 const newItem = transaction.mutations[0].modified
328 await api.createTodo(newItem)
329 // Trigger refetch to sync server state
330 await collection.utils.refetch()
332```
333​
334```ts
335// Insert handler with sync wait (Electric Collection)
336onInsert: async ({ transaction, collection }) => {
337 const newItem = transaction.mutations[0].modified
338 const result = await api.createTodo(newItem)
339 // Wait for txid to sync
340 await collection.utils.awaitTxId(result.txid)
342```
343​
344```ts
345// Insert handler with multiple items
346onInsert: async ({ transaction, collection }) => {
347 const items = transaction.mutations.map(m => m.modified)
348 await api.createTodos(items)
349 // Refetch to get updated data from server
350 await collection.utils.refetch()
352```
353​
354```ts
355// Insert handler with error handling
356onInsert: async ({ transaction, collection }) => {
357 try {
358 const newItem = transaction.mutations[0].modified
359 await api.createTodo(newItem)
360 } catch (error) {
361 console.error('Insert failed:', error)
362 throw error // This will cause the transaction to rollback
363 }
365```
366​
367#### Inherited from
368​
369```ts
370Omit.onInsert
371```
372​
373***
374​
375### onUpdate?
376​
377```ts
378optional onUpdate: UpdateMutationFn<T, TKey, LocalOnlyCollectionUtils>;
379```
380​
381Defined in: [packages/db/src/types.ts:1076](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1076)
382​
383Optional asynchronous handler function called before an update operation
384​
385#### Examples
386​
387```ts
388// Basic update handler
389onUpdate: async ({ transaction, collection }) => {
390 const updatedItem = transaction.mutations[0].modified
391 await api.updateTodo(updatedItem.id, updatedItem)
393```
394​
395```ts
396// Update handler with refetch (Query Collection)
397onUpdate: async ({ transaction, collection }) => {
398 const mutation = transaction.mutations[0]
399 const changes = mutation.changes // Only the changed fields
400 await api.updateTodo(mutation.original.id, changes)
401 // Trigger refetch to sync server state
402 await collection.utils.refetch()
404```
405​
406```ts
407// Update handler with sync wait (Electric Collection)
408onUpdate: async ({ transaction, collection }) => {
409 const mutation = transaction.mutations[0]
410 const result = await api.updateTodo(mutation.original.id, mutation.changes)
411 // Wait for txid to sync
412 await collection.utils.awaitTxId(result.txid)
414```
415​
416```ts
417// Update handler with multiple items
418onUpdate: async ({ transaction, collection }) => {
419 const updates = transaction.mutations.map(m => ({
420 id: m.key,
421 changes: m.changes
422 }))
423 await api.updateTodos(updates)
424 await collection.utils.refetch()
426```
427​
428```ts
429// Update handler with optimistic rollback
430onUpdate: async ({ transaction, collection }) => {
431 const mutation = transaction.mutations[0]
432 try {
433 await api.updateTodo(mutation.original.id, mutation.changes)
434 } catch (error) {
435 // Transaction will automatically rollback optimistic changes
436 console.error('Update failed, rolling back:', error)
437 throw error
438 }
440```
441​
442#### Inherited from
443​
444```ts
445Omit.onUpdate
446```
447​
448***
449​
450### schema?
451​
452```ts
453optional schema: TSchema;
454```
455​
456Defined in: [packages/db/src/types.ts:888](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L888)
457​
458#### Inherited from
459​
460```ts
461Omit.schema
462```
463​
464***
465​
466### syncMode?
467​
468```ts
469optional syncMode: SyncMode;
470```
471​
472Defined in: [packages/db/src/types.ts:971](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L971)
473​
474The mode of sync to use for the collection.
475​
476#### Default
477​
478`eager`
479​
480#### Description
481​
482- `eager`: syncs all data immediately on preload
483- `on-demand`: syncs data in incremental snapshots when the collection is queried
484The exact implementation of the sync mode is up to the sync implementation.
485​
486#### Inherited from
487​
488[`BaseCollectionConfig`](BaseCollectionConfig.md).[`syncMode`](BaseCollectionConfig.md#syncmode)
489​
490***
491​
492### utils?
493​
494```ts
495optional utils: LocalOnlyCollectionUtils;
496```
497​
498Defined in: [packages/db/src/types.ts:1139](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1139)
499​
500#### Inherited from
501​
502```ts
503Omit.utils
504```