https://github.com/scriptraccoon/local-storage-stores
Svelte stores that sync with localStorage
https://github.com/scriptraccoon/local-storage-stores
Last synced: 15 days ago
JSON representation
Svelte stores that sync with localStorage
- Host: GitHub
- URL: https://github.com/scriptraccoon/local-storage-stores
- Owner: ScriptRaccoon
- License: mit
- Created: 2023-12-25T00:36:19.000Z (over 2 years ago)
- Default Branch: main
- Last Pushed: 2024-01-26T00:04:15.000Z (over 2 years ago)
- Last Synced: 2024-05-30T16:49:56.203Z (about 2 years ago)
- Language: Svelte
- Homepage: https://localstoragestore.netlify.app
- Size: 19.5 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Local Storage Stores in Svelte
This repo provides a general function `local_store` in `src/lib/stores.ts` (see also below) that generates stores that will be synced with the browser's localStorage. This can be used to persist user preferences easily. The Svelte app demonstrates this with a couple of examples.
https://localstoragestore.netlify.app
## Code
```typescript
function local_store(
key: string,
default_value: T,
update: (value: T) => void = () => {}
): Writable {
let initial_value: T
try {
const has_stored_value = localStorage.getItem(key) !== null
initial_value = has_stored_value
? JSON.parse(localStorage.getItem(key)!)
: default_value
} catch (_) {
initial_value = default_value
}
const store = writable(initial_value)
store.subscribe((value: T) => {
localStorage.setItem(key, JSON.stringify(value))
update(value)
})
return store
}
```
## SvelteKit considerations
For SvelteKit applications, make sure to always check if `browser=true` before using the localStorage, since otherwise you will run into an error: the server has no `localStorage` global.