Unsuccessful shot at using localStorage

It might work in a browser but not server side
This commit is contained in:
Giulio Alessandrini 2021-08-03 09:44:09 +02:00
parent 396b865b05
commit 9d439e85a4

View File

@ -1,3 +1,31 @@
import { onMount } from 'svelte';
import { writable } from "svelte/store"; import { writable } from "svelte/store";
const localStore = (key, initial) => {
const toString = (value) => JSON.stringify(value, null, 2);
const toObject = JSON.parse;
if(process.browser) {
if (localStorage.getItem(key) === null) {
localStorage.setItem(key, toString(initial))
}
const saved = toObject(localStorage.getItem(key));
const { subscribe, set, update } = writable(saved);
return {
subscribe,
set: value => {
// both return and save in the local storage
localStorage.setItem(key, toString(value));
return set(value)
},
update
}
}
}
// export const todos = localStore('todo-store', []);
console.log("here we are: " + typeof window);
export const todos = writable([]); export const todos = writable([]);