persisted-svelte-store
v0.9.3
Published
[![npm version](https://img.shields.io/npm/v/persisted-svelte-store.svg)](https://www.npmjs.com/package/persisted-svelte-store) [![license](https://img.shields.io/npm/l/persisted-svelte-store.svg)](LICENSE.md)
Downloads
3
Readme
persisted-svelte-store
A Svelte store that persists to local storage. Can sync changes across browser tabs. Is forked from joshnuss' amazing work
Installation
npm install persisted-svelte-store
Usage
Define the store:
import { persisted } from 'persisted-svelte-store'
// First param `preferences` is the local storage key.
// Second param is the initial value.
export const preferences = persisted('preferences', {
theme: 'dark',
pane: '50%',
...
})
Then, to use it:
import { get } from 'svelte/store'
import { preferences } from './stores'
preferences.subscribe(...) // subscribe to changes
preferences.update(...) // update value
preferences.set(...) // set value
get(preferences) // read value
$preferences // read value with automatic subscription
Additional options can be specified:
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 */}, // Defaults to console.error with the error object
onParseError: (raw, error) => {/* handle or rethrow */}, // Defaults to console.error with the error object
})
License
MIT