svelte-persistent-store

repository·main·Indexed 42 days ago

https://github.com/macfja/svelte-persistent-store

A Svelte store utility (v2.4.2) that persists values across page reloads and sessions. It provides built-in support for localStorage, sessionStorage, cookies, IndexedDB, and chrome.storage, as well as tools for custom storage implementations, AES-256-GCM encryption via GCMEncryption, and configurable serialization.

Tokens
5.4K
Snippets
24
Records
31
Agent score
54%

What's inside svelte-persistent-store

  1. Define a custom Storage implementation

    main

    To use a custom storage mechanism, implement the StorageInterface<T>.

    If you want your store to react to changes made to the storage outside of the current Svelte store instance, you must also implement SelfUpdateStorageInterface<T> by adding addListener and removeListener methods.

    StorageInterface Requirements:

    • getValue(key: string): T | null: Must be synchronous. Returns null if the key doesn't exist.
    • setValue(key: string, value: T): void: Saves the value.
    • deleteValue(key: string): void: Removes the value.
  2. Migration notice: 1.3.0 to 2.0.0 breaking change

    main
    Data persisted in version 1.3.0 may not be deserializable in version 2.* due to changes in data serialization. Specifically, if your persisted store contains Javascript classes, you may not be able to retrieve the data by default after upgrading. Refer to the documentation on 'How To Change Serialization' for details.
  3. Use the persist function to wrap a Svelte store

    main

    The persist function takes an existing Svelte writable store, a storage implementation, and a unique key. It returns a PersistentStore<T> which includes a delete method to clear the persisted data.

    import { persist, createLocalStorage } from "@macfja/svelte-persistent-store"
    import { writable } from "svelte/store"
    
    // Wraps a writable store with LocalStorage persistence
    let name = persist(writable("John"), createLocalStorage(), "name")
    
    $name = "Jeanne Doe"
    // On page reload, $name will still be 'Jeanne Doe'
  4. Create a persistent writable store directly

    main

    You can use the specialized writable export from @macfja/svelte-persistent-store to create a store that is automatically persisted in localStorage with a specific key.

    import { writable } from "@macfja/svelte-persistent-store"
    
    // Create a writable store, persisted in browser LocalStorage, with the key `name`
    let name = writable("name", "John")
    
    $name = "Jeanne Doe"
    // On page reload, $name will still be 'Jeanne Doe'
  5. Use persistBrowserSession for session-based persistence

    main

    If you want data to persist only for the duration of the browser session (cleared when the tab/window is closed), use persistBrowserSession.

    import { persistBrowserSession } from "@macfja/svelte-persistent-store"
    import { writable } from "svelte/store"
    
    let title = persistBrowserSession(writable("Unsaved"), "document-name")
    
    $title = "My Document"
    // On page reload, $title will still be 'My Document'
  6. Available built-in storages

    main

    The library provides 6 built-in storage implementations. You can choose the one that best fits your use case:

    • createLocalStorage(): Uses window.localStorage.
    • createSessionStorage(): Uses window.sessionStorage.
    • createCookieStorage(): Uses document.cookie.
    • createIndexedDBStorage(): Uses window.indexedDB.
    • createChromeStorage(): Uses chrome.storage.
    • createEncryptedStorage(): A wrapper that encrypts data and keys (requires wrapping another storage).
  7. Create a SessionStorage storage implementation

    main

    Returns a StorageInterface that uses window.sessionStorage.

    • listenExternalChanges: If set to true, the store will listen for the storage event to update itself when sessionStorage is modified.
    import { createSessionStorage } from 'svelte-persistent-store';
    
    const storage = createSessionStorage(true);
  8. Configure custom serialization

    main

    By default, the library uses @macfja/serializer. You can override the global serialization and deserialization logic using setSerialization. This is useful if you need to use a different format (like YAML) or custom logic for transforming data to and from strings.

    When setting custom serialization, you can also provide a function to handle class registration for the serializer.

    import { setSerialization } from 'svelte-persistent-store';
    
    setSerialization(
      (data) => JSON.stringify(data), // Custom serializer
      (input) => JSON.parse(input),  // Custom deserializer
      (classConstructor) => { /* custom class registration logic */ }
    );
  9. Make a Svelte store persistent with persist()

    main

    Use the persist function to wrap an existing Svelte Writable store. This creates a PersistentStore that automatically synchronizes its value with the provided StorageInterface using a specific key.

    When a PersistentStore is created, it immediately attempts to load the initial value from storage. If the storage supports listeners (SelfUpdateStorageInterface), the store will also react to external changes made to that storage key.

    import { writable } from 'svelte/store';
    import { persist, createLocalStorage } from 'svelte-persistent-store';
    
    const myStore = writable(0);
    const persistentStore = persist(myStore, createLocalStorage(), 'my-key');
    
    // persistentStore is now a PersistentStore<number>
    // It has all Writable methods plus .delete()
  10. Disable storage availability warnings

    main

    If you are running your Svelte application in an environment where certain storages (like localStorage) are unavailable (e.g., during Server-Side Rendering), the library will emit warnings. You can suppress these warnings by calling disableWarnings().

    import { disableWarnings } from 'svelte-persistent-store';
    
    disableWarnings();