From 6b1c047bcdd538439f87444f9d0dad840bd7e324 Mon Sep 17 00:00:00 2001 From: Nolan Lawson Date: Fri, 12 Jan 2018 22:05:57 -0800 Subject: [PATCH] more efficient localstorage store --- routes/_utils/store.js | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/routes/_utils/store.js b/routes/_utils/store.js index 47f1193..700dbec 100644 --- a/routes/_utils/store.js +++ b/routes/_utils/store.js @@ -1,21 +1,38 @@ import { Store } from 'svelte/store.js' const key = 'ui-store' - +const LS = process.browser && localStorage class LocalStorageStore extends Store { + constructor(state) { super(state) if (process.browser) { - let cached = localStorage.getItem(key) - if (cached) { - this.set(JSON.parse(cached)) + this.lastChanged = {} + let newState = {} + for (let i = 0, len = LS.length; i < len; i++) { + let key = LS.key(i) + if (key.startsWith('store_')) { + let item = LS.getItem(key) + newState[key.substring(6)] = item === 'undefined' ? undefined : JSON.parse(item) + } } + this.set(newState) + this.onchange((state, changed) => { + Object.keys(changed).forEach(change => { + if (!this._computed[change]) { // TODO: better way to ignore computed values? + this.lastChanged[change] = true + } + }) + }) } } save() { if (process.browser) { - localStorage.setItem(key, JSON.stringify(this._state)) + Object.keys(this.lastChanged).forEach(key => { + LS.setItem(`store_${key}`, JSON.stringify(this.get(key))) + }) + this.lastChanged = {} } } }