svelte-persisted-store

repository·master·Indexed 22 days ago

https://github.com/joshnuss/svelte-persisted-store

A 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.

Tokens
2.1K
Snippets
8
Records
10
Agent score
28%

What's inside svelte-persisted-store

  1. Configure persisted store options

    master

    The 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*/},
    })
  2. Use and manipulate persisted stores

    master

    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 subscription
  3. Create a persisted Svelte store

    master

    Use the persisted function to create a store that automatically saves its value to local storage.

    • The first parameter is the key used in storage.
    • The second parameter is the 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%',
      ...
    })
  4. Configure `persisted()` with `Options`

    master

    The persisted function accepts an optional Options object to customize behavior:

    OptionTypeDescription
    serializerSerializer<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'.
    syncTabsbooleanIf true (default), listens for storage events to sync changes across different browser tabs (only works with localStorage).
    onError(e: unknown) => voidDeprecated. Use onWriteError instead.
    onWriteError(e: unknown) => voidCallback triggered when writing to storage fails.
    onParseError(newValue: string | null, e: unknown) => voidCallback triggered when reading/parsing from storage fails.
    beforeRead(val: SerializerType) => StoreTypeTransformation function applied to the value after it is parsed from storage but before it is set in the store.
    beforeWrite(val: StoreType) => SerializerTypeTransformation 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
    })
  5. Create a persisted store with `persisted()`

    master

    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' }))
  6. Implement a custom `Serializer`

    master

    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
    })
  7. Define the `Options` interface

    master

    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
    }
  8. Reset a persisted store to its initial value

    master

    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()