Skip to content

Instantly share code, notes, and snippets.

@dralletje
Created April 23, 2019 16:45
Show Gist options
  • Save dralletje/0bd737c4e9915bc8a7f2a50ccf2b0a2e to your computer and use it in GitHub Desktop.
Save dralletje/0bd737c4e9915bc8a7f2a50ccf2b0a2e to your computer and use it in GitHub Desktop.
Scoped storage
let scoped_storage = (key, { storage = localStorage } = {}) => {
return {
get: ({ default = null } = {}) => {
let value_stringified = localStorage.getItem(key);
if (value_stringified == null) {
return default;
}
try {
let value = JSON.parse(value_stringified);
return value;
} catch (err) {
localStorage.removeItem(key);
return default;
}
},
set: (value) => {
let value_stringified = JSON.stringify(value);
localStorage.setItem(key, value_stringified);
},
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment