Created
October 28, 2020 09:46
-
-
Save mihael/24ab54f6e397fe2119ff01276ad72e38 to your computer and use it in GitHub Desktop.
persistent settings for Svelte
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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', {}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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