Last active
March 26, 2020 15:54
-
-
Save PotOfCoffee2Go/76068604f6ad54092acb8bad14dcb963 to your computer and use it in GitHub Desktop.
Persist values between web pages in localstorage
This file contains hidden or 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
/* | |
Persist values between web pages in localstorage | |
Handles data objects to any depth | |
usage: | |
let store = new Store; | |
let value = store.db.path.to.field.value; | |
store.update = {section: {field: value}}; | |
*/ | |
class Store { | |
constructor() { this.init(); } | |
// Reset localStorage if asked in the querystring | |
init() { | |
let params = new URLSearchParams(window.location.search); | |
if (params.get('reset')) { this.clear(); } | |
} | |
// Get localStorage.values | |
// let obj = store.db; | |
get db() { | |
return JSON.parse(localStorage.values | |
? localStorage.values | |
: this.clear()); | |
} | |
// Update localStorage.values | |
// store.update = {section: {field: value}}; | |
set update(obj) { | |
let values = this.db; | |
values = this.merge(values, obj); | |
localStorage.values = JSON.stringify(values); | |
} | |
// Deep merge `source` data object to a `target` recursively | |
// https://gist.github.com/ahtcx/0cd94e62691f539160b32ecda18af3d6 | |
merge(target, source) { | |
for (const key of Object.keys(source)) { | |
if (source[key] instanceof Object) { | |
Object.assign(source[key], this.merge(target[key], source[key])); | |
} | |
} | |
Object.assign(target || {}, source) | |
return target | |
} | |
// Reset localStorage to default values | |
clear() { | |
localStorage.clear(); | |
let database = {}; | |
localStorage.values = JSON.stringify(database); | |
return localStorage.values; | |
} | |
// Browser friendly JSON display of localStorage values | |
settings() { | |
return '<pre>\n' + JSON.stringify(this.db, null, 2) + '\n</pre>'; | |
} | |
// Save localStorage to a local file | |
exportData() { | |
return btoa(JSON.stringify({ values: this.db }, null, 2)); | |
} | |
// Read localStorage from exported file | |
importData(data) { | |
this.update = JSON.parse(data).values; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment