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

LocalStorageCollectionConfig.md

560 lines12.5 KB

1---
2id: LocalStorageCollectionConfig
3title: LocalStorageCollectionConfig
4---
5​
6Defined in: [packages/db/src/local-storage.ts:60](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L60)
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: "off" | "eager";
40```
41​
42Defined in: [packages/db/src/types.ts:667](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L667)
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:692](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L692)
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:681](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L681)
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:838](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L838)
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:646](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L646)
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:637](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L637)
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:626](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L626)
222​
223#### Inherited from
224​
225[`BaseCollectionConfig`](BaseCollectionConfig.md).[`id`](BaseCollectionConfig.md#id)
226​
227***
228​
229### onDelete?
230​
231```ts
232optional onDelete: DeleteMutationFn<T, TKey, UtilsRecord, any>;
233```
234​
235Defined in: [packages/db/src/types.ts:830](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L830)
236​
237Optional asynchronous handler function called before a delete operation
238​
239#### Param
240​
241Object containing transaction and collection information
242​
243#### Returns
244​
245Promise resolving to any value
246​
247#### Examples
248​
249```ts
250// Basic delete handler
251onDelete: async ({ transaction, collection }) => {
252 const deletedKey = transaction.mutations[0].key
253 await api.deleteTodo(deletedKey)
255```
256​
257```ts
258// Delete handler with multiple items
259onDelete: async ({ transaction, collection }) => {
260 const keysToDelete = transaction.mutations.map(m => m.key)
261 await api.deleteTodos(keysToDelete)
263```
264​
265```ts
266// Delete handler with confirmation
267onDelete: async ({ transaction, collection }) => {
268 const mutation = transaction.mutations[0]
269 const shouldDelete = await confirmDeletion(mutation.original)
270 if (!shouldDelete) {
271 throw new Error('Delete cancelled by user')
272 }
273 await api.deleteTodo(mutation.original.id)
275```
276​
277```ts
278// Delete handler with optimistic rollback
279onDelete: async ({ transaction, collection }) => {
280 const mutation = transaction.mutations[0]
281 try {
282 await api.deleteTodo(mutation.original.id)
283 } catch (error) {
284 // Transaction will automatically rollback optimistic changes
285 console.error('Delete failed, rolling back:', error)
286 throw error
287 }
289```
290​
291#### Inherited from
292​
293[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onDelete`](BaseCollectionConfig.md#ondelete)
294​
295***
296​
297### onInsert?
298​
299```ts
300optional onInsert: InsertMutationFn<T, TKey, UtilsRecord, any>;
301```
302​
303Defined in: [packages/db/src/types.ts:743](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L743)
304​
305Optional asynchronous handler function called before an insert operation
306​
307#### Param
308​
309Object containing transaction and collection information
310​
311#### Returns
312​
313Promise resolving to any value
314​
315#### Examples
316​
317```ts
318// Basic insert handler
319onInsert: async ({ transaction, collection }) => {
320 const newItem = transaction.mutations[0].modified
321 await api.createTodo(newItem)
323```
324​
325```ts
326// Insert handler with multiple items
327onInsert: async ({ transaction, collection }) => {
328 const items = transaction.mutations.map(m => m.modified)
329 await api.createTodos(items)
331```
332​
333```ts
334// Insert handler with error handling
335onInsert: async ({ transaction, collection }) => {
336 try {
337 const newItem = transaction.mutations[0].modified
338 const result = await api.createTodo(newItem)
339 return result
340 } catch (error) {
341 console.error('Insert failed:', error)
342 throw error // This will cause the transaction to fail
343 }
345```
346​
347```ts
348// Insert handler with metadata
349onInsert: async ({ transaction, collection }) => {
350 const mutation = transaction.mutations[0]
351 await api.createTodo(mutation.modified, {
352 source: mutation.metadata?.source,
353 timestamp: mutation.createdAt
354 })
356```
357​
358#### Inherited from
359​
360[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onInsert`](BaseCollectionConfig.md#oninsert)
361​
362***
363​
364### onUpdate?
365​
366```ts
367optional onUpdate: UpdateMutationFn<T, TKey, UtilsRecord, any>;
368```
369​
370Defined in: [packages/db/src/types.ts:787](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L787)
371​
372Optional asynchronous handler function called before an update operation
373​
374#### Param
375​
376Object containing transaction and collection information
377​
378#### Returns
379​
380Promise resolving to any value
381​
382#### Examples
383​
384```ts
385// Basic update handler
386onUpdate: async ({ transaction, collection }) => {
387 const updatedItem = transaction.mutations[0].modified
388 await api.updateTodo(updatedItem.id, updatedItem)
390```
391​
392```ts
393// Update handler with partial updates
394onUpdate: async ({ transaction, collection }) => {
395 const mutation = transaction.mutations[0]
396 const changes = mutation.changes // Only the changed fields
397 await api.updateTodo(mutation.original.id, changes)
399```
400​
401```ts
402// Update handler with multiple items
403onUpdate: async ({ transaction, collection }) => {
404 const updates = transaction.mutations.map(m => ({
405 id: m.key,
406 changes: m.changes
407 }))
408 await api.updateTodos(updates)
410```
411​
412```ts
413// Update handler with optimistic rollback
414onUpdate: async ({ transaction, collection }) => {
415 const mutation = transaction.mutations[0]
416 try {
417 await api.updateTodo(mutation.original.id, mutation.changes)
418 } catch (error) {
419 // Transaction will automatically rollback optimistic changes
420 console.error('Update failed, rolling back:', error)
421 throw error
422 }
424```
425​
426#### Inherited from
427​
428[`BaseCollectionConfig`](BaseCollectionConfig.md).[`onUpdate`](BaseCollectionConfig.md#onupdate)
429​
430***
431​
432### parser?
433​
434```ts
435optional parser: Parser;
436```
437​
438Defined in: [packages/db/src/local-storage.ts:86](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L86)
439​
440Parser to use for serializing and deserializing data to and from storage
441Defaults to JSON
442​
443***
444​
445### schema?
446​
447```ts
448optional schema: TSchema;
449```
450​
451Defined in: [packages/db/src/types.ts:627](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L627)
452​
453#### Inherited from
454​
455[`BaseCollectionConfig`](BaseCollectionConfig.md).[`schema`](BaseCollectionConfig.md#schema)
456​
457***
458​
459### startSync?
460​
461```ts
462optional startSync: boolean;
463```
464​
465Defined in: [packages/db/src/types.ts:657](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L657)
466​
467Whether to eagerly start syncing on collection creation.
468When true, syncing begins immediately. When false, syncing starts when the first subscriber attaches.
469​
470Note: Even with startSync=true, collections will pause syncing when there are no active
471subscribers (typically when components querying the collection unmount), resuming when new
472subscribers attach. This preserves normal staleTime/gcTime behavior.
473​
474#### Default
475​
476```ts
477false
478```
479​
480#### Inherited from
481​
482[`BaseCollectionConfig`](BaseCollectionConfig.md).[`startSync`](BaseCollectionConfig.md#startsync)
483​
484***
485​
486### storage?
487​
488```ts
489optional storage: StorageApi;
490```
491​
492Defined in: [packages/db/src/local-storage.ts:74](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L74)
493​
494Storage API to use (defaults to window.localStorage)
495Can be any object that implements the Storage interface (e.g., sessionStorage)
496​
497***
498​
499### storageEventApi?
500​
501```ts
502optional storageEventApi: StorageEventApi;
503```
504​
505Defined in: [packages/db/src/local-storage.ts:80](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L80)
506​
507Storage event API to use for cross-tab synchronization (defaults to window)
508Can be any object that implements addEventListener/removeEventListener for storage events
509​
510***
511​
512### storageKey
513​
514```ts
515storageKey: string;
516```
517​
518Defined in: [packages/db/src/local-storage.ts:68](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L68)
519​
520The key to use for storing the collection data in localStorage/sessionStorage
521​
522***
523​
524### syncMode?
525​
526```ts
527optional syncMode: SyncMode;
528```
529​
530Defined in: [packages/db/src/types.ts:701](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L701)
531​
532The mode of sync to use for the collection.
533​
534#### Default
535​
536`eager`
537​
538#### Description
539​
540- `eager`: syncs all data immediately on preload
541- `on-demand`: syncs data in incremental snapshots when the collection is queried
542The exact implementation of the sync mode is up to the sync implementation.
543​
544#### Inherited from
545​
546[`BaseCollectionConfig`](BaseCollectionConfig.md).[`syncMode`](BaseCollectionConfig.md#syncmode)
547​
548***
549​
550### utils?
551​
552```ts
553optional utils: UtilsRecord;
554```
555​
556Defined in: [packages/db/src/types.ts:840](https://github.com/TanStack/db/blob/main/packages/db/src/types.ts#L840)
557​
558#### Inherited from
559​
560[`BaseCollectionConfig`](BaseCollectionConfig.md).[`utils`](BaseCollectionConfig.md#utils)