Open History to see the last commit
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:816](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L816)
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:841](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L841)
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:830](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L830)
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:1036](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1036)
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:795](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L795)
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 grace period.
167Pending preloads retain the collection until they settle. Preloading ready
168data refreshes the retention period. A non-positive or non-finite value
169disables automatic garbage collection.
170
171#### Inherited from
172
173[`BaseCollectionConfig`](BaseCollectionConfig.md).[`gcTime`](BaseCollectionConfig.md#gctime)
174
175***
176
177### getKey()
178
179```ts
180getKey: (item) => TKey;
181```
182
183Defined in: [packages/db/src/types.ts:786](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L786)
184
185Function to extract the ID from an object
186This is required for update/delete operations which now only accept IDs
187
188#### Parameters
189
190##### item
191
192`T`
193
194The item to extract the ID from
195
196#### Returns
197
198`TKey`
199
200The ID string for the item
201
202#### Example
203
204```ts
205// For a collection with a 'uuid' field as the primary key
206getKey: (item) => item.uuid
207```
208
209#### Inherited from
210
211[`BaseCollectionConfig`](BaseCollectionConfig.md).[`getKey`](BaseCollectionConfig.md#getkey)
212
213***
214
215### id?
216
217```ts
218optional id: string;
219```
220
221Defined in: [packages/db/src/types.ts:775](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L775)
222
223#### Inherited from
224
225[`BaseCollectionConfig`](BaseCollectionConfig.md).[`id`](BaseCollectionConfig.md#id)
226
227***
228
229### onDelete?
230
231```ts
232optional onDelete:
233 | DeleteMutationFn<T, TKey, UtilsRecord, void>
234| DeleteMutationFn<T, TKey, UtilsRecord, any>;
235```
236
237Defined in: [packages/db/src/types.ts:1025](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1025)
238
239Optional asynchronous handler function called before a delete operation
240Returning a value is deprecated; coordinate synchronization through collection utilities instead.
241
242#### Examples
243
244```ts
245// Basic delete handler
246onDelete: async ({ transaction, collection }) => {
247 const deletedKey = transaction.mutations[0].key
248 await api.deleteTodo(deletedKey)
249}
250```
251
252```ts
253// Delete handler with refetch (Query Collection)
254onDelete: async ({ transaction, collection }) => {
255 const keysToDelete = transaction.mutations.map(m => m.key)
256 await api.deleteTodos(keysToDelete)
257 // Trigger refetch to sync server state
258 await collection.utils.refetch()
259 // Prevent the pre-1.0 compatibility wrapper from refetching again.
260 return { refetch: false }
261}
262```
263
264```ts
265// Delete handler with sync wait (Electric Collection)
266onDelete: async ({ transaction, collection }) => {
267 const mutation = transaction.mutations[0]
268 const result = await api.deleteTodo(mutation.original.id)
269 // Wait for txid to sync
270 await collection.utils.awaitTxId(result.txid)
271}
272```
273
274```ts
275// Delete handler with confirmation
276onDelete: async ({ transaction, collection }) => {
277 const mutation = transaction.mutations[0]
278 const shouldDelete = await confirmDeletion(mutation.original)
279 if (!shouldDelete) {
280 throw new Error('Delete cancelled by user')
281 }
282 await api.deleteTodo(mutation.original.id)
283}
284```
285
286```ts
287// Delete handler with optimistic rollback
288onDelete: async ({ transaction, collection }) => {
289 const mutation = transaction.mutations[0]
290 try {
291 await api.deleteTodo(mutation.original.id)
292 } catch (error) {
293 // Transaction will automatically rollback optimistic changes
294 console.error('Delete failed, rolling back:', error)
295 throw error
296 }
297}
298```
299
300#### Inherited from
301
302[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onDelete`](BaseCollectionConfig.md#ondelete)
303
304***
305
306### onInsert?
307
308```ts
309optional onInsert:
310 | InsertMutationFn<T, TKey, UtilsRecord, void>
311| InsertMutationFn<T, TKey, UtilsRecord, any>;
312```
313
314Defined in: [packages/db/src/types.ts:904](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L904)
315
316Optional asynchronous handler function called before an insert operation
317Returning a value is deprecated; coordinate synchronization through collection utilities instead.
318
319#### Examples
320
321```ts
322// Basic insert handler
323onInsert: async ({ transaction, collection }) => {
324 const newItem = transaction.mutations[0].modified
325 await api.createTodo(newItem)
326}
327```
328
329```ts
330// Insert handler with refetch (Query Collection)
331onInsert: async ({ transaction, collection }) => {
332 const newItem = transaction.mutations[0].modified
333 await api.createTodo(newItem)
334 // Trigger refetch to sync server state
335 await collection.utils.refetch()
336 // Prevent the pre-1.0 compatibility wrapper from refetching again.
337 return { refetch: false }
338}
339```
340
341```ts
342// Insert handler with sync wait (Electric Collection)
343onInsert: async ({ transaction, collection }) => {
344 const newItem = transaction.mutations[0].modified
345 const result = await api.createTodo(newItem)
346 // Wait for txid to sync
347 await collection.utils.awaitTxId(result.txid)
348}
349```
350
351```ts
352// Insert handler with multiple items
353onInsert: async ({ transaction, collection }) => {
354 const items = transaction.mutations.map(m => m.modified)
355 await api.createTodos(items)
356 // Refetch to get updated data from server
357 await collection.utils.refetch()
358 return { refetch: false }
359}
360```
361
362```ts
363// Insert handler with error handling
364onInsert: async ({ transaction, collection }) => {
365 try {
366 const newItem = transaction.mutations[0].modified
367 await api.createTodo(newItem)
368 } catch (error) {
369 console.error('Insert failed:', error)
370 throw error // This will cause the transaction to rollback
371 }
372}
373```
374
375#### Inherited from
376
377[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onInsert`](BaseCollectionConfig.md#oninsert)
378
379***
380
381### onUpdate?
382
383```ts
384optional onUpdate:
385 | UpdateMutationFn<T, TKey, UtilsRecord, void>
386| UpdateMutationFn<T, TKey, UtilsRecord, any>;
387```
388
389Defined in: [packages/db/src/types.ts:966](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L966)
390
391Optional asynchronous handler function called before an update operation
392Returning a value is deprecated; coordinate synchronization through collection utilities instead.
393
394#### Examples
395
396```ts
397// Basic update handler
398onUpdate: async ({ transaction, collection }) => {
399 const updatedItem = transaction.mutations[0].modified
400 await api.updateTodo(updatedItem.id, updatedItem)
401}
402```
403
404```ts
405// Update handler with refetch (Query Collection)
406onUpdate: async ({ transaction, collection }) => {
407 const mutation = transaction.mutations[0]
408 const changes = mutation.changes // Only the changed fields
409 await api.updateTodo(mutation.original.id, changes)
410 // Trigger refetch to sync server state
411 await collection.utils.refetch()
412 // Prevent the pre-1.0 compatibility wrapper from refetching again.
413 return { refetch: false }
414}
415```
416
417```ts
418// Update handler with sync wait (Electric Collection)
419onUpdate: async ({ transaction, collection }) => {
420 const mutation = transaction.mutations[0]
421 const result = await api.updateTodo(mutation.original.id, mutation.changes)
422 // Wait for txid to sync
423 await collection.utils.awaitTxId(result.txid)
424}
425```
426
427```ts
428// Update handler with multiple items
429onUpdate: async ({ transaction, collection }) => {
430 const updates = transaction.mutations.map(m => ({
431 id: m.key,
432 changes: m.changes
433 }))
434 await api.updateTodos(updates)
435 await collection.utils.refetch()
436 return { refetch: false }
437}
438```
439
440```ts
441// Update handler with optimistic rollback
442onUpdate: async ({ transaction, collection }) => {
443 const mutation = transaction.mutations[0]
444 try {
445 await api.updateTodo(mutation.original.id, mutation.changes)
446 } catch (error) {
447 // Transaction will automatically rollback optimistic changes
448 console.error('Update failed, rolling back:', error)
449 throw error
450 }
451}
452```
453
454#### Inherited from
455
456[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onUpdate`](BaseCollectionConfig.md#onupdate)
457
458***
459
460### parser?
461
462```ts
463optional parser: Parser;
464```
465
466Defined in: [packages/db/src/local-storage.ts:140](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L140)
467
468Parser to use for serializing and deserializing data to and from storage
469Defaults to JSON
470
471***
472
473### schema?
474
475```ts
476optional schema: TSchema;
477```
478
479Defined in: [packages/db/src/types.ts:776](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L776)
480
481#### Inherited from
482
483[`BaseCollectionConfig`](BaseCollectionConfig.md).[`schema`](BaseCollectionConfig.md#schema)
484
485***
486
487### startSync?
488
489```ts
490optional startSync: boolean;
491```
492
493Defined in: [packages/db/src/types.ts:806](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L806)
494
495Whether to eagerly start syncing on collection creation.
496When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches.
497
498Note: Even with startSync=true, collections will pause syncing when there are no active
499subscribers (typically when components querying the collection unmount), resuming when new
500subscribers attach. This preserves normal staleTime/gcTime behavior.
501
502#### Default
503
504```ts
505false
506```
507
508#### Inherited from
509
510[`BaseCollectionConfig`](BaseCollectionConfig.md).[`startSync`](BaseCollectionConfig.md#startsync)
511
512***
513
514### storage?
515
516```ts
517optional storage: StorageApi;
518```
519
520Defined in: [packages/db/src/local-storage.ts:128](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L128)
521
522Storage API to use (defaults to window.localStorage)
523Can be any object that implements the Storage interface (e.g., sessionStorage)
524
525***
526
527### storageEventApi?
528
529```ts
530optional storageEventApi: StorageEventApi;
531```
532
533Defined in: [packages/db/src/local-storage.ts:134](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L134)
534
535Storage event API to use for cross-tab synchronization (defaults to window)
536Can be any object that implements addEventListener/removeEventListener for storage events
537
538***
539
540### storageKey
541
542```ts
543storageKey: string;
544```
545
546Defined in: [packages/db/src/local-storage.ts:122](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L122)
547
548The key to use for storing the collection data in localStorage/sessionStorage
549
550***
551
552### syncMode?
553
554```ts
555optional syncMode: SyncMode;
556```
557
558Defined in: [packages/db/src/types.ts:850](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L850)
559
560The mode of sync to use for the collection.
561
562#### Default
563
564`eager`
565
566#### Description
567
568- `eager`: syncs all data immediately on preload
569- `on-demand`: syncs data in incremental snapshots when the collection is queried
570The exact implementation of the sync mode is up to the sync implementation.
571
572#### Inherited from
573
574[`BaseCollectionConfig`](BaseCollectionConfig.md).[`syncMode`](BaseCollectionConfig.md#syncmode)
575
576***
577
578### utils?
579
580```ts
581optional utils: UtilsRecord;
582```
583
584Defined in: [packages/db/src/types.ts:1038](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L1038)
585
586#### Inherited from
587
588[`BaseCollectionConfig`](BaseCollectionConfig.md).[`utils`](BaseCollectionConfig.md#utils)