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

LocalStorageCollectionConfig.md

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