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

localStorageCollectionOptions.md

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