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

LocalStorageCollectionConfig.md

558 lines12.3 KB

1---
2id: LocalStorageCollectionConfig
3title: LocalStorageCollectionConfig
4---
5​
6# Interface: LocalStorageCollectionConfig\<T, TSchema, TKey\>
7​
8Defined in: [packages/db/src/local-storage.ts:58](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L58)
9​
10Configuration interface for localStorage collection options
11​
12## Extends
13​
14- [`BaseCollectionConfig`](BaseCollectionConfig.md)\<`T`, `TKey`, `TSchema`\>
15​
16## Type Parameters
17​
18### T
19​
20`T` *extends* `object` = `object`
21​
22The type of items in the collection
23​
24### TSchema
25​
26`TSchema` *extends* `StandardSchemaV1` = `never`
27​
28The schema type for validation
29​
30### TKey
31​
32`TKey` *extends* `string` \| `number` = `string` \| `number`
33​
34The type of the key returned by `getKey`
35​
36## Properties
37​
38### autoIndex?
39​
40```ts
41optional autoIndex: "off" | "eager";
42```
43​
44Defined in: [packages/db/src/types.ts:571](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L571)
45​
46Auto-indexing mode for the collection.
47When enabled, indexes will be automatically created for simple where expressions.
48​
49#### Default
50​
51```ts
52"off"
53```
54​
55#### Description
56​
57- "off": No automatic indexing (default). Use explicit indexes for better bundle size.
58- "eager": Automatically create indexes for simple where expressions in subscribeChanges.
59 Requires setting defaultIndexType.
60​
61#### Inherited from
62​
63[`BaseCollectionConfig`](BaseCollectionConfig.md).[`autoIndex`](BaseCollectionConfig.md#autoindex)
64​
65***
66​
67### compare()?
68​
69```ts
70optional compare: (x, y) => number;
71```
72​
73Defined in: [packages/db/src/types.ts:596](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L596)
74​
75Optional function to compare two items.
76This is used to order the items in the collection.
77​
78#### Parameters
79​
80##### x
81​
82`T`
83​
84The first item to compare
85​
86##### y
87​
88`T`
89​
90The second item to compare
91​
92#### Returns
93​
94`number`
95​
96A number indicating the order of the items
97​
98#### Example
99​
100```ts
101// For a collection with a 'createdAt' field
102compare: (x, y) => x.createdAt.getTime() - y.createdAt.getTime()
103```
104​
105#### Inherited from
106​
107[`BaseCollectionConfig`](BaseCollectionConfig.md).[`compare`](BaseCollectionConfig.md#compare)
108​
109***
110​
111### defaultIndexType?
112​
113```ts
114optional defaultIndexType: IndexConstructor<TKey>;
115```
116​
117Defined in: [packages/db/src/types.ts:585](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L585)
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[`BaseCollectionConfig`](BaseCollectionConfig.md).[`defaultIndexType`](BaseCollectionConfig.md#defaultindextype)
136​
137***
138​
139### defaultStringCollation?
140​
141```ts
142optional defaultStringCollation: StringCollationConfig;
143```
144​
145Defined in: [packages/db/src/types.ts:742](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L742)
146​
147Specifies how to compare data in the collection.
148This should be configured to match data ordering on the backend.
149E.g., when using the Electric DB collection these options
150 should match the database's collation settings.
151​
152#### Inherited from
153​
154[`BaseCollectionConfig`](BaseCollectionConfig.md).[`defaultStringCollation`](BaseCollectionConfig.md#defaultstringcollation)
155​
156***
157​
158### gcTime?
159​
160```ts
161optional gcTime: number;
162```
163​
164Defined in: [packages/db/src/types.ts:550](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L550)
165​
166Time in milliseconds after which the collection will be garbage collected
167when it has no active subscribers. Defaults to 5 minutes (300000ms).
168​
169#### Inherited from
170​
171[`BaseCollectionConfig`](BaseCollectionConfig.md).[`gcTime`](BaseCollectionConfig.md#gctime)
172​
173***
174​
175### getKey()
176​
177```ts
178getKey: (item) => TKey;
179```
180​
181Defined in: [packages/db/src/types.ts:545](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L545)
182​
183Function to extract the ID from an object
184This is required for update/delete operations which now only accept IDs
185​
186#### Parameters
187​
188##### item
189​
190`T`
191​
192The item to extract the ID from
193​
194#### Returns
195​
196`TKey`
197​
198The ID string for the item
199​
200#### Example
201​
202```ts
203// For a collection with a 'uuid' field as the primary key
204getKey: (item) => item.uuid
205```
206​
207#### Inherited from
208​
209[`BaseCollectionConfig`](BaseCollectionConfig.md).[`getKey`](BaseCollectionConfig.md#getkey)
210​
211***
212​
213### id?
214​
215```ts
216optional id: string;
217```
218​
219Defined in: [packages/db/src/types.ts:534](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L534)
220​
221#### Inherited from
222​
223[`BaseCollectionConfig`](BaseCollectionConfig.md).[`id`](BaseCollectionConfig.md#id)
224​
225***
226​
227### onDelete?
228​
229```ts
230optional onDelete: DeleteMutationFn<T, TKey, UtilsRecord, any>;
231```
232​
233Defined in: [packages/db/src/types.ts:734](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L734)
234​
235Optional asynchronous handler function called before a delete operation
236​
237#### Param
238​
239Object containing transaction and collection information
240​
241#### Returns
242​
243Promise resolving to any value
244​
245#### Examples
246​
247```ts
248// Basic delete handler
249onDelete: async ({ transaction, collection }) => {
250 const deletedKey = transaction.mutations[0].key
251 await api.deleteTodo(deletedKey)
253```
254​
255```ts
256// Delete handler with multiple items
257onDelete: async ({ transaction, collection }) => {
258 const keysToDelete = transaction.mutations.map(m => m.key)
259 await api.deleteTodos(keysToDelete)
261```
262​
263```ts
264// Delete handler with confirmation
265onDelete: async ({ transaction, collection }) => {
266 const mutation = transaction.mutations[0]
267 const shouldDelete = await confirmDeletion(mutation.original)
268 if (!shouldDelete) {
269 throw new Error('Delete cancelled by user')
270 }
271 await api.deleteTodo(mutation.original.id)
273```
274​
275```ts
276// Delete handler with optimistic rollback
277onDelete: async ({ transaction, collection }) => {
278 const mutation = transaction.mutations[0]
279 try {
280 await api.deleteTodo(mutation.original.id)
281 } catch (error) {
282 // Transaction will automatically rollback optimistic changes
283 console.error('Delete failed, rolling back:', error)
284 throw error
285 }
287```
288​
289#### Inherited from
290​
291[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onDelete`](BaseCollectionConfig.md#ondelete)
292​
293***
294​
295### onInsert?
296​
297```ts
298optional onInsert: InsertMutationFn<T, TKey, UtilsRecord, any>;
299```
300​
301Defined in: [packages/db/src/types.ts:647](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L647)
302​
303Optional asynchronous handler function called before an insert operation
304​
305#### Param
306​
307Object containing transaction and collection information
308​
309#### Returns
310​
311Promise resolving to any value
312​
313#### Examples
314​
315```ts
316// Basic insert handler
317onInsert: async ({ transaction, collection }) => {
318 const newItem = transaction.mutations[0].modified
319 await api.createTodo(newItem)
321```
322​
323```ts
324// Insert handler with multiple items
325onInsert: async ({ transaction, collection }) => {
326 const items = transaction.mutations.map(m => m.modified)
327 await api.createTodos(items)
329```
330​
331```ts
332// Insert handler with error handling
333onInsert: async ({ transaction, collection }) => {
334 try {
335 const newItem = transaction.mutations[0].modified
336 const result = await api.createTodo(newItem)
337 return result
338 } catch (error) {
339 console.error('Insert failed:', error)
340 throw error // This will cause the transaction to fail
341 }
343```
344​
345```ts
346// Insert handler with metadata
347onInsert: async ({ transaction, collection }) => {
348 const mutation = transaction.mutations[0]
349 await api.createTodo(mutation.modified, {
350 source: mutation.metadata?.source,
351 timestamp: mutation.createdAt
352 })
354```
355​
356#### Inherited from
357​
358[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onInsert`](BaseCollectionConfig.md#oninsert)
359​
360***
361​
362### onUpdate?
363​
364```ts
365optional onUpdate: UpdateMutationFn<T, TKey, UtilsRecord, any>;
366```
367​
368Defined in: [packages/db/src/types.ts:691](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L691)
369​
370Optional asynchronous handler function called before an update operation
371​
372#### Param
373​
374Object containing transaction and collection information
375​
376#### Returns
377​
378Promise resolving to any value
379​
380#### Examples
381​
382```ts
383// Basic update handler
384onUpdate: async ({ transaction, collection }) => {
385 const updatedItem = transaction.mutations[0].modified
386 await api.updateTodo(updatedItem.id, updatedItem)
388```
389​
390```ts
391// Update handler with partial updates
392onUpdate: async ({ transaction, collection }) => {
393 const mutation = transaction.mutations[0]
394 const changes = mutation.changes // Only the changed fields
395 await api.updateTodo(mutation.original.id, changes)
397```
398​
399```ts
400// Update handler with multiple items
401onUpdate: async ({ transaction, collection }) => {
402 const updates = transaction.mutations.map(m => ({
403 id: m.key,
404 changes: m.changes
405 }))
406 await api.updateTodos(updates)
408```
409​
410```ts
411// Update handler with optimistic rollback
412onUpdate: async ({ transaction, collection }) => {
413 const mutation = transaction.mutations[0]
414 try {
415 await api.updateTodo(mutation.original.id, mutation.changes)
416 } catch (error) {
417 // Transaction will automatically rollback optimistic changes
418 console.error('Update failed, rolling back:', error)
419 throw error
420 }
422```
423​
424#### Inherited from
425​
426[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onUpdate`](BaseCollectionConfig.md#onupdate)
427​
428***
429​
430### parser?
431​
432```ts
433optional parser: Parser;
434```
435​
436Defined in: [packages/db/src/local-storage.ts:84](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L84)
437​
438Parser to use for serializing and deserializing data to and from storage
439Defaults to JSON
440​
441***
442​
443### schema?
444​
445```ts
446optional schema: TSchema;
447```
448​
449Defined in: [packages/db/src/types.ts:535](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L535)
450​
451#### Inherited from
452​
453[`BaseCollectionConfig`](BaseCollectionConfig.md).[`schema`](BaseCollectionConfig.md#schema)
454​
455***
456​
457### startSync?
458​
459```ts
460optional startSync: boolean;
461```
462​
463Defined in: [packages/db/src/types.ts:561](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L561)
464​
465Whether to eagerly start syncing on collection creation.
466When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches.
467​
468Note: Even with startSync=true, collections will pause syncing when there are no active
469subscribers (typically when components querying the collection unmount), resuming when new
470subscribers attach. This preserves normal staleTime/gcTime behavior.
471​
472#### Default
473​
474```ts
475false
476```
477​
478#### Inherited from
479​
480[`BaseCollectionConfig`](BaseCollectionConfig.md).[`startSync`](BaseCollectionConfig.md#startsync)
481​
482***
483​
484### storage?
485​
486```ts
487optional storage: StorageApi;
488```
489​
490Defined in: [packages/db/src/local-storage.ts:72](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L72)
491​
492Storage API to use (defaults to window.localStorage)
493Can be any object that implements the Storage interface (e.g., sessionStorage)
494​
495***
496​
497### storageEventApi?
498​
499```ts
500optional storageEventApi: StorageEventApi;
501```
502​
503Defined in: [packages/db/src/local-storage.ts:78](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L78)
504​
505Storage event API to use for cross-tab synchronization (defaults to window)
506Can be any object that implements addEventListener/removeEventListener for storage events
507​
508***
509​
510### storageKey
511​
512```ts
513storageKey: string;
514```
515​
516Defined in: [packages/db/src/local-storage.ts:66](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L66)
517​
518The key to use for storing the collection data in localStorage/sessionStorage
519​
520***
521​
522### syncMode?
523​
524```ts
525optional syncMode: SyncMode;
526```
527​
528Defined in: [packages/db/src/types.ts:605](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L605)
529​
530The mode of sync to use for the collection.
531​
532#### Default
533​
534`eager`
535​
536#### Description
537​
538- `eager`: syncs all data immediately on preload
539- `on-demand`: syncs data in incremental snapshots when the collection is queried
540The exact implementation of the sync mode is up to the sync implementation.
541​
542#### Inherited from
543​
544[`BaseCollectionConfig`](BaseCollectionConfig.md).[`syncMode`](BaseCollectionConfig.md#syncmode)
545​
546***
547​
548### utils?
549​
550```ts
551optional utils: UtilsRecord;
552```
553​
554Defined in: [packages/db/src/types.ts:744](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L744)
555​
556#### Inherited from
557​
558[`BaseCollectionConfig`](BaseCollectionConfig.md).[`utils`](BaseCollectionConfig.md#utils)