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

local-storage-collection.md

402 lines14.8 KB

1---
2title: LocalStorage Collection
3---
4​
5LocalStorage collections store small amounts of local-only state that persists
6across browser sessions and syncs between Collections in one tab and across
7browser tabs.
8​
9## Overview
10​
11The `localStorageCollectionOptions` allows you to create collections that:
12- Persist data to localStorage (or sessionStorage)
13- Automatically sync across browser tabs using storage events
14- Synchronize active same-tab Collections sharing one storage object and key
15- Support optimistic updates with automatic rollback on errors
16- Store all data under a single localStorage key
17- Work with any storage API that matches the localStorage interface
18​
19## Installation
20​
21LocalStorage collections are included in the core TanStack DB package:
22​
23```bash
24npm install @tanstack/react-db
25```
26​
27## Basic Usage
28​
29```typescript
30import { createCollection } from '@tanstack/react-db'
31import { localStorageCollectionOptions } from '@tanstack/react-db'
32​
33const userPreferencesCollection = createCollection(
34 localStorageCollectionOptions({
35 id: 'user-preferences',
36 storageKey: 'app-user-prefs',
37 getKey: (item) => item.id,
38 })
40```
41​
42### Direct Local Mutations
43​
44**Important:** LocalStorage collections work differently than server-synced collections. With LocalStorage collections, you **directly mutate state** by calling methods like `collection.insert()`, `collection.update()`, and `collection.delete()` — that's all you need to do. The changes are immediately applied to your local data and automatically persisted to localStorage.
45​
46This is different from collections that sync with a server (like Query Collection), where mutation handlers send data to a backend. With LocalStorage collections, everything stays local:
47​
48```typescript
49// Just call the methods directly - automatically persisted to localStorage
50userPreferencesCollection.insert({ id: 'theme', mode: 'dark' })
51userPreferencesCollection.update('theme', (draft) => { draft.mode = 'light' })
52userPreferencesCollection.delete('theme')
53```
54​
55## Configuration Options
56​
57The `localStorageCollectionOptions` function accepts the following options:
58​
59### Required Options
60​
61- `id`: Unique identifier for the collection
62- `storageKey`: The localStorage key where all collection data is stored
63- `getKey`: Function to extract the unique key from an item
64​
65### Optional Options
66​
67- `schema`: [Standard Schema](https://standardschema.dev) compatible schema (e.g., Zod, Effect) for client-side validation
68- `storage`: Custom storage implementation (defaults to `localStorage`). Can be `sessionStorage` or any object with the localStorage API
69- `storageEventApi`: Event API for subscribing to storage events (defaults to `window`). Enables custom cross-tab, cross-window, or cross-process synchronization
70- `parser`: Object with `parse` and `stringify` methods for storage (defaults to `JSON`). Use a library such as superjson to store values that JSON cannot represent
71- `onInsert`: Optional handler function called when items are inserted
72- `onUpdate`: Optional handler function called when items are updated
73- `onDelete`: Optional handler function called when items are deleted
74​
75## Synchronization
76​
77LocalStorage collections sync across browser tabs through storage events:
78​
79```typescript
80const settingsCollection = createCollection(
81 localStorageCollectionOptions({
82 id: 'settings',
83 storageKey: 'app-settings',
84 getKey: (item) => item.id,
85 })
87​
88// Changes in one tab are automatically reflected in all other tabs
89// This works automatically via storage events
90```
91​
92Two active Collections created with fresh options also sync in the same tab
93when they use the same `storage` object and `storageKey`. A successful automatic
94write, manual acceptance, or `clearStorage()` updates both public snapshots
95without waiting for a browser event. A Collection's pending optimistic rows
96remain visible until their own mutations settle. The same-tab mechanism does
97not connect distinct custom Storage wrapper objects, even if those wrappers
98access the same underlying bytes.
99​
100The default JSON parser keeps a value authored by the writer in its original
101JavaScript form until that Collection restores or another write replaces that
102row. A disjoint peer write does not change the authored value. For example, a
103writer can still hold a `Date`, while a peer and a freshly restored Collection
104see its JSON string. With a custom parser, an authored row is read back after a
105successful write so the writer also sees any value that parser normalized.
106​
107With the default parser (the built-in `JSON` object), an insert or update must
108contain only values that a restore can return. The Collection rejects a row
109that contains any of these:
110​
111- a function or symbol, or an enumerable property with a symbol key
112- `NaN`, `Infinity`, or `-Infinity`, including as a `Number` object
113- `undefined` or a hole as an array entry, or an array with properties other
114 than its elements
115- a `Map`, `Set`, `WeakMap`, `WeakSet`, `RegExp`, `Promise`, `ArrayBuffer`,
116 `SharedArrayBuffer`, or typed array
117​
118The rejected mutation's `when('settled')` promise rejects with
119`SerializationError`. Nothing is written to storage and the optimistic row
120rolls back. An automatic write's `onInsert` or `onUpdate` handler does not run;
121a manual `acceptMutations` call rejects with the same error.
122​
123Some values are accepted and normalized. A value with a `toJSON` method, such
124as `Date`, is stored as that method's result, and the checks above apply to
125that result. A property whose value (or `toJSON` result) is `undefined` is
126stored as an absent property, and `-0` is stored as `0`. Non-enumerable
127properties are not row data and are not stored. A class instance is stored as
128its own enumerable properties, so a restored row is a plain object without the
129class's methods. A custom `parser`, such as one that supports `Map`, defines
130its own value rules; only its `stringify` errors reject a write. This includes
131a parser object that wraps `JSON.stringify`.
132​
133Automatic mutations in one Collection persist in mutation order, even if their
134optional handlers finish in another order. A handler that rejects does not write
135its mutation. Other tabs see accepted changes when their storage events arrive.
136Without a handler or earlier pending write, a direct mutation writes to
137localStorage before the mutation method returns. A later handler failure rejects
138its transaction promptly, even if an earlier handler is still pending.
139​
140A handler can start another mutation on the same Collection, then return without
141awaiting that mutation's `when('settled')` promise. Do not await that promise or a
142later `acceptMutations()` call inside the earlier handler. Those writes wait for
143the earlier handler to return, so awaiting them would leave both pending.
144​
145Each write stores a complete storage snapshot under one storage key. A
146write preserves disjoint peer rows already present in storage, even when that
147peer's event has not arrived yet. Truly simultaneous writes from separate tabs
148are not an atomic transaction; localStorage has no compare-and-swap operation.
149​
150Startup requires a valid stored snapshot. Malformed JSON or a row missing its
151version information puts the Collection in an error state and leaves the stored
152bytes intact. Each stored row needs an object value, a string version token,
153and a storage key that decodes to the same identity as `getKey` for its data.
154New writes encode string and number keys with a type prefix; restore also
155accepts legacy unprefixed string keys. Two entries that decode to one identity
156are malformed. Repair or remove
157the invalid value, then restart the Collection. A Collection restoring rows can
158receive a same-tab peer write from a subscriber during that restore; the peer's
159accepted row remains visible when the Collection becomes ready.
160`utils.clearStorage()` removes the stored snapshot and immediately publishes
161removal of accepted rows to active same-tab Collections. A pending optimistic
162mutation can remain visible and later persist. Edit the Collection through its
163mutation methods;
164direct same-tab edits to its storage key do not produce browser storage events.
165Use an IndexedDB Collection when several tabs need stronger write coordination.
166​
167If storage cannot be read, the mutation rejects and existing stored rows remain.
168A failed storage-event read leaves current Collection rows unchanged until a
169later event can read storage successfully.
170​
171## Using SessionStorage
172​
173You can use `sessionStorage` instead of `localStorage` for session-only persistence:
174​
175```typescript
176const sessionCollection = createCollection(
177 localStorageCollectionOptions({
178 id: 'session-data',
179 storageKey: 'session-key',
180 storage: sessionStorage, // Use sessionStorage instead
181 getKey: (item) => item.id,
182 })
184```
185​
186## Custom Storage Backend
187​
188Provide any storage implementation that matches the localStorage API:
189​
190```typescript
191// Example: Custom storage wrapper with encryption
192const encryptedStorage = {
193 getItem(key: string) {
194 const encrypted = localStorage.getItem(key)
195 return encrypted ? decrypt(encrypted) : null
196 },
197 setItem(key: string, value: string) {
198 localStorage.setItem(key, encrypt(value))
199 },
200 removeItem(key: string) {
201 localStorage.removeItem(key)
202 },
204​
205const secureCollection = createCollection(
206 localStorageCollectionOptions({
207 id: 'secure-data',
208 storageKey: 'encrypted-key',
209 storage: encryptedStorage,
210 getKey: (item) => item.id,
211 })
213```
214​
215### Cross-Tab Sync with Custom Storage
216​
217The `storageEventApi` option (defaults to `window`) allows the collection to subscribe to storage events for cross-tab synchronization. A custom storage implementation can provide this API to enable custom cross-tab, cross-window, or cross-process sync:
218​
219```typescript
220// Example: Custom storage event API for cross-process sync
221const customStorageEventApi = {
222 addEventListener(event: string, handler: (e: StorageEvent) => void) {
223 // Custom event subscription logic
224 // Could be IPC, WebSocket, or any other mechanism
225 myCustomEventBus.on('storage-change', handler)
226 },
227 removeEventListener(event: string, handler: (e: StorageEvent) => void) {
228 myCustomEventBus.off('storage-change', handler)
229 },
231​
232const syncedCollection = createCollection(
233 localStorageCollectionOptions({
234 id: 'synced-data',
235 storageKey: 'data-key',
236 storage: customStorage,
237 storageEventApi: customStorageEventApi, // Custom event API
238 getKey: (item) => item.id,
239 })
241```
242​
243This enables synchronization across different contexts beyond just browser tabs, such as:
244- Cross-process communication in Electron apps
245- WebSocket-based sync across multiple browser windows
246- Custom IPC mechanisms in desktop applications
247​
248## Mutation Handlers
249​
250Mutation handlers are **completely optional**. Data will persist to localStorage whether or not you provide handlers:
251​
252```typescript
253const preferencesCollection = createCollection(
254 localStorageCollectionOptions({
255 id: 'preferences',
256 storageKey: 'user-prefs',
257 getKey: (item) => item.id,
258 // Optional: Add custom logic when preferences are updated
259 onUpdate: async ({ transaction }) => {
260 const { modified } = transaction.mutations[0]
261 console.log('Preference updated:', modified)
262 // Maybe send analytics or trigger other side effects
263 },
264 })
266```
267​
268## Manual Transactions
269​
270When using LocalStorage collections with manual transactions (created via `createTransaction`), call `utils.acceptMutations()` in `mutationFn`. Manual acceptance joins the same write order, and the transaction's persistence receipt waits for the storage write even if the returned Promise is not awaited. Await it when later work in `mutationFn` depends on the storage write:
271​
272```typescript
273import { createTransaction } from '@tanstack/react-db'
274​
275const localData = createCollection(
276 localStorageCollectionOptions({
277 id: 'form-draft',
278 storageKey: 'draft-data',
279 getKey: (item) => item.id,
280 })
282​
283const serverCollection = createCollection(
284 queryCollectionOptions({
285 queryKey: ['items'],
286 queryFn: async () => api.items.getAll(),
287 getKey: (item) => item.id,
288 onInsert: async ({ transaction }) => {
289 await api.items.create(transaction.mutations[0].modified)
290 },
291 })
293​
294const tx = createTransaction({
295 mutationFn: async ({ transaction }) => {
296 // Handle server collection mutations explicitly in mutationFn
297 await Promise.all(
298 transaction.mutations
299 .filter((m) => m.collection === serverCollection)
300 .map((m) => api.items.create(m.modified))
301 )
302​
303 // After server mutations succeed, persist local collection mutations
304 await localData.utils.acceptMutations(transaction)
305 },
306})
307​
308// Apply mutations to both collections in one transaction
309tx.mutate(() => {
310 localData.insert({ id: 'draft-1', data: '...' })
311 serverCollection.insert({ id: '1', name: 'Item' })
312})
313​
314await tx.commit()
315```
316​
317Create fresh `localStorageCollectionOptions()` for each direct
318`createCollection()` call. One options object contains state owned by one
319Collection and throws if used to create a second. The same `DbClient`
320collection descriptor can still materialize fresh options for separate clients.
321​
322## Complete Example
323​
324```typescript
325import { createCollection, eq } from '@tanstack/react-db'
326import { localStorageCollectionOptions } from '@tanstack/react-db'
327import { useLiveQuery } from '@tanstack/react-db'
328import { z } from 'zod'
329​
330// Define schema
331const userPrefsSchema = z.object({
332 id: z.string(),
333 theme: z.enum(['light', 'dark', 'auto']),
334 language: z.string(),
335 notifications: z.boolean(),
336})
337​
338type UserPrefs = z.infer<typeof userPrefsSchema>
339​
340// Create collection
341export const userPreferencesCollection = createCollection(
342 localStorageCollectionOptions({
343 id: 'user-preferences',
344 storageKey: 'app-user-prefs',
345 getKey: (item) => item.id,
346 schema: userPrefsSchema,
347 })
349​
350// Use in component
351function SettingsPanel() {
352 const { data: prefs } = useLiveQuery({
353 query: (q) =>
354 q
355 .from({ pref: userPreferencesCollection })
356 .where(({ pref }) => eq(pref.id, 'current-user')),
357 })
358​
359 const currentPrefs = prefs[0]
360​
361 const updateTheme = (theme: 'light' | 'dark' | 'auto') => {
362 if (currentPrefs) {
363 userPreferencesCollection.update(currentPrefs.id, (draft) => {
364 draft.theme = theme
365 })
366 } else {
367 userPreferencesCollection.insert({
368 id: 'current-user',
369 theme,
370 language: 'en',
371 notifications: true,
372 })
373 }
374 }
375​
376 return (
377 <div>
378 <h2>Theme: {currentPrefs?.theme}</h2>
379 <button onClick={() => updateTheme('dark')}>Dark Mode</button>
380 <button onClick={() => updateTheme('light')}>Light Mode</button>
381 </div>
382 )
384```
385​
386## Use Cases
387​
388LocalStorage collections are perfect for:
389- User preferences and settings
390- UI state that should persist across sessions
391- Form drafts
392- Recently viewed items
393- User-specific configurations
394- Small amounts of cached data
395​
396## Learn More
397​
398- [IndexedDB Collection](./indexed-db-collection.md)
399​
400- [Optimistic Mutations](../guides/mutations.md)
401- [Live Queries](../guides/live-queries.md)
402- [LocalOnly Collection](./local-only-collection.md)