Install svelte-persisted-store via npm
masterInstall the package using npm to add persisted Svelte stores to your project.
npm install svelte-persisted-storerepository·master·Indexed 22 days ago
https://github.com/joshnuss/svelte-persisted-storeA Svelte store utility that automatically persists state to local or session storage with built-in support for cross-tab synchronization. It provides the `persisted()` function to create stores that extend the standard Svelte Writable interface with a `reset()` method and configurable options for serialization, storage engines, and data transformation.
Install the package using npm to add persisted Svelte stores to your project.
npm install svelte-persisted-storeThe persisted function accepts an optional third argument for configuration.
Key options include:
serializer: The object used to serialize/deserialize data (defaults to JSON).storage: The storage engine to use. Use 'session' for sessionStorage; defaults to 'local' (localStorage).syncTabs: Boolean indicating whether to sync changes across browser tabs (defaults to true).onWriteError: Callback function triggered when writing to storage fails. Defaults to console.error.onParseError: Callback function triggered when parsing storage data fails. Defaults to console.error.beforeRead: Function to transform the value after it is read from storage but before it is set in the store.beforeWrite: Function to transform the value after it is updated in the store but before it is written to storage.import * as devalue from 'devalue'
// third parameter is options
export const preferences = persisted('local-storage-key', 'default-value', {
serializer: devalue, // defaults to `JSON`
storage: 'session', // 'session' for sessionStorage, defaults to 'local'
syncTabs: true, // choose whether to sync localStorage across tabs, default is true
onWriteError: (error) => {/* handle or rethrow */},
onParseError: (raw, error) => {/* handle or rethrow */},
beforeRead: (value) => {/* change value after serialization but before setting store to return value*/},
beforeWrite: (value) => {/* change value after writing to store, but before writing return value to local storage*/},
})A persisted store behaves like a standard Svelte store. You can use standard Svelte store methods and syntax to interact with it.
import { get } from 'svelte/store'
import { preferences } from './stores'
preferences.subscribe(...) // subscribe to changes
preferences.update(...) // update value
preferences.set(...) // set value
preferences.reset() // reset to initial value
get(preferences) // read value
$preferences // read value with automatic subscriptionUse the persisted function to create a store that automatically saves its value to local storage.
key used in storage.initialValue used if no value is found in storage.import { persisted } from 'svelte-persisted-store'
// First param `preferences` is the local storage key.
// Second param is the initial value.
export const preferences = persisted('preferences', {
theme: 'dark',
pane: '50%',
...
})The persisted function accepts an optional Options object to customize behavior:
| Option | Type | Description |
|---|---|---|
serializer | Serializer<T> | Custom object with parse(text: string): T and stringify(object: T): string methods. Defaults to JSON. |
storage | 'local' | 'session' | Which Web Storage API to use. Defaults to 'local'. |
syncTabs | boolean | If true (default), listens for storage events to sync changes across different browser tabs (only works with localStorage). |
onError | (e: unknown) => void | Deprecated. Use onWriteError instead. |
onWriteError | (e: unknown) => void | Callback triggered when writing to storage fails. |
onParseError | (newValue: string | null, e: unknown) => void | Callback triggered when reading/parsing from storage fails. |
beforeRead | (val: SerializerType) => StoreType | Transformation function applied to the value after it is parsed from storage but before it is set in the store. |
beforeWrite | (val: StoreType) => SerializerType | Transformation function applied to the value before it is passed to the serializer for storage. |
import { persisted } from 'svelte-persisted-store'
const myStore = persisted('my-key', 0, {
storage: 'session',
syncTabs: false,
onWriteError: (e) => console.error('Write failed', e),
onParseError: (val, e) => console.error('Parse failed for', val, e),
beforeWrite: (val) => val + 1,
beforeRead: (val) => val - 1
})Use the persisted function to create a Svelte store that automatically synchronizes its value with localStorage or sessionStorage.
When a value is updated in the store, it is serialized and written to storage. On initialization, the store attempts to read and parse the existing value from storage. If no value exists or parsing fails, it falls back to the initialValue.
Note: The writable() function is deprecated. Use persisted() instead.
import { persisted } from 'svelte-persisted-store'
const myStore = persisted('my-key', { foo: 'bar' })
// Usage
myStore.set({ foo: 'baz' })
myStore.update(val => ({ ...val, foo: 'qux' }))If you need to store data in a format other than JSON (e.g., a custom string format or a different serialization library), provide a Serializer object in the options.serializer field.
import { persisted } from 'svelte-persisted-store'
const mySerializer = {
parse: (text: string) => text.split(','),
stringify: (arr: string[]) => arr.join(',')
}
const myStore = persisted('my-list', ['a', 'b'], {
serializer: mySerializer
})The Persisted<T> type represents the object returned by persisted(). It is a Svelte Writable<T> that includes a reset() method.
export interface Persisted<T> extends Writable<T> {
reset: () => void
}The Options interface defines the configuration available to the persisted function.
export interface Options<StoreType, SerializerType> {
serializer?: Serializer<SerializerType>
storage?: StorageType
syncTabs?: boolean
onError?: (e: unknown) => void
onWriteError?: (e: unknown) => void
onParseError?: (newValue: string | null, e: unknown) => void
beforeRead?: (val: SerializerType) => StoreType
beforeWrite?: (val: StoreType) => SerializerType
}The Persisted<T> interface extends the standard Svelte Writable<T> interface by adding a reset() method. Calling reset() sets the store's value back to the initialValue provided when the store was first created and updates the underlying storage.
const myStore = persisted('my-key', 'initial-value')
// Later...
myStore.reset()