Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/joshnuss/svelte-persisted-store
A Svelte store that persists to localStorage
https://github.com/joshnuss/svelte-persisted-store
localstorage pubsub sessionstorage svelte
Last synced: 22 days ago
JSON representation
A Svelte store that persists to localStorage
- Host: GitHub
- URL: https://github.com/joshnuss/svelte-persisted-store
- Owner: joshnuss
- License: mit
- Created: 2020-07-03T05:10:23.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2024-02-08T17:07:09.000Z (9 months ago)
- Last Synced: 2024-04-14T03:14:26.259Z (7 months ago)
- Topics: localstorage, pubsub, sessionstorage, svelte
- Language: TypeScript
- Homepage:
- Size: 1.34 MB
- Stars: 838
- Watchers: 10
- Forks: 38
- Open Issues: 11
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE.md
Awesome Lists containing this project
README
[![npm version](https://img.shields.io/npm/v/svelte-persisted-store.svg)](https://www.npmjs.com/package/svelte-persisted-store) [![license](https://img.shields.io/npm/l/svelte-persisted-store.svg)](LICENSE.md) [![codecov](https://codecov.io/gh/joshnuss/svelte-persisted-store/branch/master/graph/badge.svg?token=GU607D2YRQ)](https://codecov.io/gh/joshnuss/svelte-persisted-store)
# svelte-persisted-store
A Svelte store that persists to local storage. Can sync changes across browser tabs.
## Installation
```bash
npm install svelte-persisted-store
```## Usage
Define the store:
```javascript
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%',
...
})
```Then, to use it:
```javascript
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
```Additional options can be specified:
```javascript
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
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*/},
})
```## License
MIT