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

localStorageCollectionOptions.md

242 lines7.4 KB

1---
2id: localStorageCollectionOptions
3title: localStorageCollectionOptions
4---
5​
6## Call Signature
7​
8```ts
9function localStorageCollectionOptions<T, TKey>(config): CollectionConfig<InferSchemaOutput<T>, TKey, T, LocalStorageCollectionUtils> & object;
10```
11​
12Defined in: [packages/db/src/local-storage.ts:386](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L386)
13​
14Creates localStorage collection options for use with a standard Collection
15​
16This function creates a collection that persists data to localStorage/sessionStorage
17and synchronizes changes across browser tabs using storage events. Active
18Collections sharing this Storage object and storage key also synchronize
19writes in the same tab, without waiting for a browser event.
20Create fresh options for each direct `createCollection()` call. One options
21object contains state owned by one Collection and cannot be reused.
22​
23**Fallback Behavior:**
24​
25When localStorage is not available (e.g., in server-side rendering environments),
26this function automatically falls back to an in-memory storage implementation.
27This prevents errors during module initialization and allows the collection to
28work in any environment, though data will not persist across page reloads or
29be shared across tabs when using the in-memory fallback.
30​
31**Using with Manual Transactions:**
32​
33For manual transactions, call `utils.acceptMutations()` in your transaction's `mutationFn`
34to persist changes made during `tx.mutate()`. The transaction receipt waits for this work even
35when the call is not awaited. Await it when later mutationFn work depends on the storage write.
36​
37### Type Parameters
38​
39#### T
40​
41`T` *extends* `StandardSchemaV1`\<`unknown`, `unknown`\>
42​
43#### TKey
44​
45`TKey` *extends* `string` \| `number` = `string` \| `number`
46​
47### Parameters
48​
49#### config
50​
51[`LocalStorageCollectionConfig`](../interfaces/LocalStorageCollectionConfig.md)\<[`InferSchemaOutput`](../type-aliases/InferSchemaOutput.md)\<`T`\>, `T`, `TKey`\> & `object`
52​
53Configuration options for the localStorage collection
54​
55### Returns
56​
57[`CollectionConfig`](../interfaces/CollectionConfig.md)\<[`InferSchemaOutput`](../type-aliases/InferSchemaOutput.md)\<`T`\>, `TKey`, `T`, [`LocalStorageCollectionUtils`](../interfaces/LocalStorageCollectionUtils.md)\> & `object`
58​
59Collection options with utilities including clearStorage, getStorageSize, and acceptMutations
60​
61### Examples
62​
63```ts
64// Basic localStorage collection
65const collection = createCollection(
66 localStorageCollectionOptions({
67 storageKey: 'todos',
68 getKey: (item) => item.id,
69 })
71```
72​
73```ts
74// localStorage collection with custom storage
75const collection = createCollection(
76 localStorageCollectionOptions({
77 storageKey: 'todos',
78 storage: window.sessionStorage, // Use sessionStorage instead
79 getKey: (item) => item.id,
80 })
82```
83​
84```ts
85// localStorage collection with mutation handlers
86const collection = createCollection(
87 localStorageCollectionOptions({
88 storageKey: 'todos',
89 getKey: (item) => item.id,
90 onInsert: async ({ transaction }) => {
91 console.log('Item inserted:', transaction.mutations[0].modified)
92 },
93 })
95```
96​
97```ts
98// Using with manual transactions
99const localSettings = createCollection(
100 localStorageCollectionOptions({
101 storageKey: 'user-settings',
102 getKey: (item) => item.id,
103 })
105​
106const tx = createTransaction({
107 mutationFn: async ({ transaction }) => {
108 // Use settings data in API call
109 const settingsMutations = transaction.mutations.filter(m => m.collection === localSettings)
110 await api.updateUserProfile({ settings: settingsMutations[0]?.modified })
111​
112 // Persist local-storage mutations after API success
113 await localSettings.utils.acceptMutations(transaction)
114 }
115})
116​
117tx.mutate(() => {
118 localSettings.insert({ id: 'theme', value: 'dark' })
119 apiCollection.insert({ id: 2, data: 'profile data' })
120})
121​
122await tx.commit()
123```
124​
125## Call Signature
126​
127```ts
128function localStorageCollectionOptions<T, TKey>(config): CollectionConfig<T, TKey, never, LocalStorageCollectionUtils> & object;
129```
130​
131Defined in: [packages/db/src/local-storage.ts:406](https://github.com/TanStack/db/blob/main/packages/db/src/local-storage.ts#L406)
132​
133Creates localStorage collection options for use with a standard Collection
134​
135This function creates a collection that persists data to localStorage/sessionStorage
136and synchronizes changes across browser tabs using storage events. Active
137Collections sharing this Storage object and storage key also synchronize
138writes in the same tab, without waiting for a browser event.
139Create fresh options for each direct `createCollection()` call. One options
140object contains state owned by one Collection and cannot be reused.
141​
142**Fallback Behavior:**
143​
144When localStorage is not available (e.g., in server-side rendering environments),
145this function automatically falls back to an in-memory storage implementation.
146This prevents errors during module initialization and allows the collection to
147work in any environment, though data will not persist across page reloads or
148be shared across tabs when using the in-memory fallback.
149​
150**Using with Manual Transactions:**
151​
152For manual transactions, call `utils.acceptMutations()` in your transaction's `mutationFn`
153to persist changes made during `tx.mutate()`. The transaction receipt waits for this work even
154when the call is not awaited. Await it when later mutationFn work depends on the storage write.
155​
156### Type Parameters
157​
158#### T
159​
160`T` *extends* `object`
161​
162#### TKey
163​
164`TKey` *extends* `string` \| `number` = `string` \| `number`
165​
166### Parameters
167​
168#### config
169​
170[`LocalStorageCollectionConfig`](../interfaces/LocalStorageCollectionConfig.md)\<`T`, `never`, `TKey`\> & `object`
171​
172Configuration options for the localStorage collection
173​
174### Returns
175​
176[`CollectionConfig`](../interfaces/CollectionConfig.md)\<`T`, `TKey`, `never`, [`LocalStorageCollectionUtils`](../interfaces/LocalStorageCollectionUtils.md)\> & `object`
177​
178Collection options with utilities including clearStorage, getStorageSize, and acceptMutations
179​
180### Examples
181​
182```ts
183// Basic localStorage collection
184const collection = createCollection(
185 localStorageCollectionOptions({
186 storageKey: 'todos',
187 getKey: (item) => item.id,
188 })
190```
191​
192```ts
193// localStorage collection with custom storage
194const collection = createCollection(
195 localStorageCollectionOptions({
196 storageKey: 'todos',
197 storage: window.sessionStorage, // Use sessionStorage instead
198 getKey: (item) => item.id,
199 })
201```
202​
203```ts
204// localStorage collection with mutation handlers
205const collection = createCollection(
206 localStorageCollectionOptions({
207 storageKey: 'todos',
208 getKey: (item) => item.id,
209 onInsert: async ({ transaction }) => {
210 console.log('Item inserted:', transaction.mutations[0].modified)
211 },
212 })
214```
215​
216```ts
217// Using with manual transactions
218const localSettings = createCollection(
219 localStorageCollectionOptions({
220 storageKey: 'user-settings',
221 getKey: (item) => item.id,
222 })
224​
225const tx = createTransaction({
226 mutationFn: async ({ transaction }) => {
227 // Use settings data in API call
228 const settingsMutations = transaction.mutations.filter(m => m.collection === localSettings)
229 await api.updateUserProfile({ settings: settingsMutations[0]?.modified })
230​
231 // Persist local-storage mutations after API success
232 await localSettings.utils.acceptMutations(transaction)
233 }
234})
235​
236tx.mutate(() => {
237 localSettings.insert({ id: 'theme', value: 'dark' })
238 apiCollection.insert({ id: 2, data: 'profile data' })
239})
240​
241await tx.commit()
242```