Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/bechii/svelte-store2storage
https://github.com/bechii/svelte-store2storage
localstorage sessionstorage store svelte
Last synced: about 1 month ago
JSON representation
- Host: GitHub
- URL: https://github.com/bechii/svelte-store2storage
- Owner: bechii
- License: mit
- Created: 2022-09-27T11:47:49.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-12-20T11:24:35.000Z (about 1 year ago)
- Last Synced: 2024-10-20T05:04:47.689Z (3 months ago)
- Topics: localstorage, sessionstorage, store, svelte
- Language: JavaScript
- Homepage: https://www.npmjs.com/package/svelte-store2storage
- Size: 39.1 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[![NPM Version](https://img.shields.io/npm/v/svelte-store2storage.svg?style=for-the-badge)](https://www.npmjs.com/package/svelte-store2storage)
# svelte-store2storage
A functional approach to sync stores to local or session storage
## 💾 Install
```bash
npm i svelte-store2storage
```## âš¡ Quick example
```
// stores.ts
import { writable } from 'svelte/store';
import { syncToLocalStorage } from 'svelte-store2storage';export const personStore = writable({
name: 'John Doe'
});syncToLocalStorage(personStore, 'storage_key');
```## 🔨 API
```
interface EncodingOptions {
encode?: (value: T) => string | undefined;
decode?: (value: string) => T;
}syncToLocalStorage(store: IStore, key: string, encodingOptions?: EncodingOptions): () => void
syncToSessionStorage(store: IStore, key: string, encodingOptions?: EncodingOptions): () => void
``````
// stores.tsimport { BooleanStore } from 'butik';
export const store = new BooleanStore(false);
syncToLocalStorage(store, 'storage_key');
```Utility methods to sync stores with localStorage and sessionStorage which returns a callback to unsync again.
Besides receiving a store and a storage key as parameters, they can also have custom encoding logic.
If no encoding options are passed, JSON.stringify and JSON.parse is used.
If you are using [SvelteKit](https://github.com/sveltejs/kit), remember to wrap the methods in `if (browser)`.