Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/leodog896/svelte-persistent
Svelte writables for local & session storage
https://github.com/leodog896/svelte-persistent
localstorage sessionstorage storage svelte
Last synced: 25 days ago
JSON representation
Svelte writables for local & session storage
- Host: GitHub
- URL: https://github.com/leodog896/svelte-persistent
- Owner: LeoDog896
- License: mit
- Created: 2022-09-11T00:50:03.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2023-09-04T16:54:26.000Z (over 1 year ago)
- Last Synced: 2025-01-08T23:42:42.765Z (about 1 month ago)
- Topics: localstorage, sessionstorage, storage, svelte
- Language: TypeScript
- Homepage: https://leodog896.github.io/svelte-persistent
- Size: 116 KB
- Stars: 2
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.txt
Awesome Lists containing this project
README
# svelte-persistent
Demo: https://leodog896.github.io/svelte-persistent/
localStorage and sessionStorage writables for SvelteKit & Svelte. SSR safe.
```bash
npm i -D svelte-persistent
``````ts
import { localStore, sessionStore } from 'svelte-persistent';// store(key, default).
const local = localStore('content', 'local');
const session = sessionStore('content', 'session');
```## Or JSON objects
```ts
import { localStore } from 'svelte-persistent'; // or sessionStorage!const objectStore = localStore('content', {
foo: 'bar'
});
```## Why?
When calling `localStorage.set("key", value)`, this is a browser call.
SvelteKit uses SSR (server-side rendering) which doesn't allow DOM calls during the rendering process.```js
localStorage.set('hello', 'world'); // localStorage is not defined!
```With this in mind, in order to use localStorage effectively, you need to run it using `onMount`.
```js
import { onMount } from 'svelte';onMount(() => {
localStorage.set('hello', 'world'); // works!
});
```But, then you run into two problems:
- you may want the data for SSR beforehand, so that way you have placeholder data before the page loads.
- localStorage doesn't act as a reactive store, and won't react to sets/getsThis library solves both problems with a simple to use svelte store around local OR session storage.