svelte-local-storage-store
A Svelte store that persists to local storage. Supports changes across multiple tabs.
Installation
npm install svelte-local-storage-store
Usage
Define the store:
import { persisted } from 'svelte-local-storage-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 when you want to use the store:
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
You can also optionally set the serializer
or storage
type:
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'
})
License
MIT