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

LocalStorageCollectionConfig.md

580 lines13.8 KB

1---
2id: LocalStorageCollectionConfig
3title: LocalStorageCollectionConfig
4---
5​
6Defined in: [packages/db/src/local-storage.ts:114](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L114)
7​
8Configuration interface for localStorage collection options
9​
10## Extends
11​
12- [`BaseCollectionConfig`](BaseCollectionConfig.md)\<`T`, `TKey`, `TSchema`\>
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[`BaseCollectionConfig`](BaseCollectionConfig.md).[`compare`](BaseCollectionConfig.md#compare)
106​
107***
108​
109### defaultIndexType?
110​
111```ts
112optional defaultIndexType: IndexConstructor<TKey>;
113```
114​
115Defined in: [packages/db/src/types.ts:951](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L951)
116​
117Default index type to use when creating indexes without an explicit type.
118Required for auto-indexing. Import from '@tanstack/db'.
119​
120#### Example
121​
122```ts
123import { BasicIndex } from '@tanstack/db'
124const collection = createCollection({
125 defaultIndexType: BasicIndex,
126 autoIndex: 'eager',
127 // ...
128})
129```
130​
131#### Inherited from
132​
133[`BaseCollectionConfig`](BaseCollectionConfig.md).[`defaultIndexType`](BaseCollectionConfig.md#defaultindextype)
134​
135***
136​
137### defaultStringCollation?
138​
139```ts
140optional defaultStringCollation: StringCollationConfig;
141```
142​
143Defined in: [packages/db/src/types.ts:1137](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1137)
144​
145Specifies how to compare data in the collection.
146This should be configured to match data ordering on the backend.
147E.g., when using the Electric DB collection these options
148 should match the database's collation settings.
149​
150#### Inherited from
151​
152[`BaseCollectionConfig`](BaseCollectionConfig.md).[`defaultStringCollation`](BaseCollectionConfig.md#defaultstringcollation)
153​
154***
155​
156### gcTime?
157​
158```ts
159optional gcTime: number;
160```
161​
162Defined in: [packages/db/src/types.ts:916](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L916)
163​
164Time in milliseconds after which the collection will be garbage collected
165when it has no active subscribers. Defaults to 5 minutes (300000ms).
166Sync started without subscribers gets a minimum 50ms handoff grace period
167until a subscriber attaches. After the last subscriber leaves, gcTime
168applies without that startup minimum.
169Pending preloads retain the collection until they settle. Preloading ready
170data refreshes the retention period. A persisting transaction that touches
171the collection also retains it, and the period starts again when the last
172one completes or fails, preserving any remaining startup grace. Pending
173manual transactions do not retain it; keep a subscription for draft
174visibility until commit or rollback. Rolling
175back a manual transaction that stayed pending preserves the existing GC
176deadline. Cleanup runs at a host idle opportunity after the delay.
177A non-positive or non-finite value
178disables automatic garbage collection.
179​
180#### Inherited from
181​
182[`BaseCollectionConfig`](BaseCollectionConfig.md).[`gcTime`](BaseCollectionConfig.md#gctime)
183​
184***
185​
186### getKey()
187​
188```ts
189getKey: (item) => TKey;
190```
191​
192Defined in: [packages/db/src/types.ts:898](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L898)
193​
194Function to extract the ID from an object
195This is required for update/delete operations which now only accept IDs
196​
197#### Parameters
198​
199##### item
200​
201`T`
202​
203The item to extract the ID from
204​
205#### Returns
206​
207`TKey`
208​
209The ID string for the item
210​
211#### Example
212​
213```ts
214// For a collection with a 'uuid' field as the primary key
215getKey: (item) => item.uuid
216```
217​
218#### Inherited from
219​
220[`BaseCollectionConfig`](BaseCollectionConfig.md).[`getKey`](BaseCollectionConfig.md#getkey)
221​
222***
223​
224### id?
225​
226```ts
227optional id: string;
228```
229​
230Defined in: [packages/db/src/types.ts:887](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L887)
231​
232#### Inherited from
233​
234[`BaseCollectionConfig`](BaseCollectionConfig.md).[`id`](BaseCollectionConfig.md#id)
235​
236***
237​
238### onDelete?
239​
240```ts
241optional onDelete: DeleteMutationFn<T, TKey, UtilsRecord>;
242```
243​
244Defined in: [packages/db/src/types.ts:1129](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1129)
245​
246Optional asynchronous handler function called before a delete operation
247​
248#### Examples
249​
250```ts
251// Basic delete handler
252onDelete: async ({ transaction, collection }) => {
253 const deletedKey = transaction.mutations[0].key
254 await api.deleteTodo(deletedKey)
256```
257​
258```ts
259// Delete handler with refetch (Query Collection)
260onDelete: async ({ transaction, collection }) => {
261 const keysToDelete = transaction.mutations.map(m => m.key)
262 await api.deleteTodos(keysToDelete)
263 // Trigger refetch to sync server state
264 await collection.utils.refetch()
266```
267​
268```ts
269// Delete handler with sync wait (Electric Collection)
270onDelete: async ({ transaction, collection }) => {
271 const mutation = transaction.mutations[0]
272 const result = await api.deleteTodo(mutation.original.id)
273 // Wait for txid to sync
274 await collection.utils.awaitTxId(result.txid)
276```
277​
278```ts
279// Delete handler with confirmation
280onDelete: async ({ transaction, collection }) => {
281 const mutation = transaction.mutations[0]
282 const shouldDelete = await confirmDeletion(mutation.original)
283 if (!shouldDelete) {
284 throw new Error('Delete cancelled by user')
285 }
286 await api.deleteTodo(mutation.original.id)
288```
289​
290```ts
291// Delete handler with optimistic rollback
292onDelete: async ({ transaction, collection }) => {
293 const mutation = transaction.mutations[0]
294 try {
295 await api.deleteTodo(mutation.original.id)
296 } catch (error) {
297 // Transaction will automatically rollback optimistic changes
298 console.error('Delete failed, rolling back:', error)
299 throw error
300 }
302```
303​
304#### Inherited from
305​
306[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onDelete`](BaseCollectionConfig.md#ondelete)
307​
308***
309​
310### onInsert?
311​
312```ts
313optional onInsert: InsertMutationFn<T, TKey, UtilsRecord>;
314```
315​
316Defined in: [packages/db/src/types.ts:1021](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1021)
317​
318Optional asynchronous handler function called before an insert operation
319​
320#### Examples
321​
322```ts
323// Basic insert handler
324onInsert: async ({ transaction, collection }) => {
325 const newItem = transaction.mutations[0].modified
326 await api.createTodo(newItem)
328```
329​
330```ts
331// Insert handler with refetch (Query Collection)
332onInsert: async ({ transaction, collection }) => {
333 const newItem = transaction.mutations[0].modified
334 await api.createTodo(newItem)
335 // Trigger refetch to sync server state
336 await collection.utils.refetch()
338```
339​
340```ts
341// Insert handler with sync wait (Electric Collection)
342onInsert: async ({ transaction, collection }) => {
343 const newItem = transaction.mutations[0].modified
344 const result = await api.createTodo(newItem)
345 // Wait for txid to sync
346 await collection.utils.awaitTxId(result.txid)
348```
349​
350```ts
351// Insert handler with multiple items
352onInsert: async ({ transaction, collection }) => {
353 const items = transaction.mutations.map(m => m.modified)
354 await api.createTodos(items)
355 // Refetch to get updated data from server
356 await collection.utils.refetch()
358```
359​
360```ts
361// Insert handler with error handling
362onInsert: async ({ transaction, collection }) => {
363 try {
364 const newItem = transaction.mutations[0].modified
365 await api.createTodo(newItem)
366 } catch (error) {
367 console.error('Insert failed:', error)
368 throw error // This will cause the transaction to rollback
369 }
371```
372​
373#### Inherited from
374​
375[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onInsert`](BaseCollectionConfig.md#oninsert)
376​
377***
378​
379### onUpdate?
380​
381```ts
382optional onUpdate: UpdateMutationFn<T, TKey, UtilsRecord>;
383```
384​
385Defined in: [packages/db/src/types.ts:1076](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1076)
386​
387Optional asynchronous handler function called before an update operation
388​
389#### Examples
390​
391```ts
392// Basic update handler
393onUpdate: async ({ transaction, collection }) => {
394 const updatedItem = transaction.mutations[0].modified
395 await api.updateTodo(updatedItem.id, updatedItem)
397```
398​
399```ts
400// Update handler with refetch (Query Collection)
401onUpdate: async ({ transaction, collection }) => {
402 const mutation = transaction.mutations[0]
403 const changes = mutation.changes // Only the changed fields
404 await api.updateTodo(mutation.original.id, changes)
405 // Trigger refetch to sync server state
406 await collection.utils.refetch()
408```
409​
410```ts
411// Update handler with sync wait (Electric Collection)
412onUpdate: async ({ transaction, collection }) => {
413 const mutation = transaction.mutations[0]
414 const result = await api.updateTodo(mutation.original.id, mutation.changes)
415 // Wait for txid to sync
416 await collection.utils.awaitTxId(result.txid)
418```
419​
420```ts
421// Update handler with multiple items
422onUpdate: async ({ transaction, collection }) => {
423 const updates = transaction.mutations.map(m => ({
424 id: m.key,
425 changes: m.changes
426 }))
427 await api.updateTodos(updates)
428 await collection.utils.refetch()
430```
431​
432```ts
433// Update handler with optimistic rollback
434onUpdate: async ({ transaction, collection }) => {
435 const mutation = transaction.mutations[0]
436 try {
437 await api.updateTodo(mutation.original.id, mutation.changes)
438 } catch (error) {
439 // Transaction will automatically rollback optimistic changes
440 console.error('Update failed, rolling back:', error)
441 throw error
442 }
444```
445​
446#### Inherited from
447​
448[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onUpdate`](BaseCollectionConfig.md#onupdate)
449​
450***
451​
452### parser?
453​
454```ts
455optional parser: Parser;
456```
457​
458Defined in: [packages/db/src/local-storage.ts:140](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L140)
459​
460Parser to use for serializing and deserializing data to and from storage
461Defaults to JSON
462​
463***
464​
465### schema?
466​
467```ts
468optional schema: TSchema;
469```
470​
471Defined in: [packages/db/src/types.ts:888](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L888)
472​
473#### Inherited from
474​
475[`BaseCollectionConfig`](BaseCollectionConfig.md).[`schema`](BaseCollectionConfig.md#schema)
476​
477***
478​
479### startSync?
480​
481```ts
482optional startSync: boolean;
483```
484​
485Defined in: [packages/db/src/types.ts:927](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L927)
486​
487Whether to eagerly start syncing on collection creation.
488When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches.
489​
490Note: Even with startSync=true, collections will pause syncing when there are no active
491subscribers (typically when components querying the collection unmount), resuming when new
492subscribers attach. This preserves normal staleTime/gcTime behavior.
493​
494#### Default
495​
496```ts
497false
498```
499​
500#### Inherited from
501​
502[`BaseCollectionConfig`](BaseCollectionConfig.md).[`startSync`](BaseCollectionConfig.md#startsync)
503​
504***
505​
506### storage?
507​
508```ts
509optional storage: StorageApi;
510```
511​
512Defined in: [packages/db/src/local-storage.ts:128](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L128)
513​
514Storage API to use (defaults to window.localStorage)
515Can be any object that implements the Storage interface (e.g., sessionStorage)
516​
517***
518​
519### storageEventApi?
520​
521```ts
522optional storageEventApi: StorageEventApi;
523```
524​
525Defined in: [packages/db/src/local-storage.ts:134](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L134)
526​
527Storage event API to use for cross-tab synchronization (defaults to window)
528Can be any object that implements addEventListener/removeEventListener for storage events
529​
530***
531​
532### storageKey
533​
534```ts
535storageKey: string;
536```
537​
538Defined in: [packages/db/src/local-storage.ts:122](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L122)
539​
540The key to use for storing the collection data in localStorage/sessionStorage
541​
542***
543​
544### syncMode?
545​
546```ts
547optional syncMode: SyncMode;
548```
549​
550Defined in: [packages/db/src/types.ts:971](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L971)
551​
552The mode of sync to use for the collection.
553​
554#### Default
555​
556`eager`
557​
558#### Description
559​
560- `eager`: syncs all data immediately on preload
561- `on-demand`: syncs data in incremental snapshots when the collection is queried
562The exact implementation of the sync mode is up to the sync implementation.
563​
564#### Inherited from
565​
566[`BaseCollectionConfig`](BaseCollectionConfig.md).[`syncMode`](BaseCollectionConfig.md#syncmode)
567​
568***
569​
570### utils?
571​
572```ts
573optional utils: UtilsRecord;
574```
575​
576Defined in: [packages/db/src/types.ts:1139](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1139)
577​
578#### Inherited from
579​
580[`BaseCollectionConfig`](BaseCollectionConfig.md).[`utils`](BaseCollectionConfig.md#utils)