Skip to content

Instantly share code, notes, and snippets.

@mihael
Created October 28, 2020 09:46
Show Gist options
  • Save mihael/24ab54f6e397fe2119ff01276ad72e38 to your computer and use it in GitHub Desktop.
Save mihael/24ab54f6e397fe2119ff01276ad72e38 to your computer and use it in GitHub Desktop.
persistent settings for Svelte
// A writable settings/data store backed by localStorage
import { writable } from 'svelte/store'
const createWritableStore = (key, startValue) => {
const { subscribe, set } = writable(startValue)
return {
subscribe,
set,
useLocalStorage: () => {
const json = localStorage.getItem(key)
if (json) {
let parsed_json = ""
try {
parsed_json = JSON.parse(json)
} catch (e) {
console.log('Error parsing json:')
console.log(e)
}
if (parsed_json) {
set(parsed_json)
}
}
subscribe(val => {
localStorage.setItem(key, JSON.stringify(val))
})
}
}
}
export const settings = createWritableStore('settings', {})
<script>
import { onMount } from 'svelte';
import { settings } from 'settings.js'
settings.useLocalStorage()
let data
function loadSettings() {
if ($settings && $settings.data) {
data = $settings.data
}
}
function saveSettings() {
if (data && $settings) {
$settings.data = data
}
}
onMount(async () => {
loadSettings()
})
</script>
Data: {data}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment