Created
April 23, 2019 16:45
-
-
Save dralletje/0bd737c4e9915bc8a7f2a50ccf2b0a2e to your computer and use it in GitHub Desktop.
Scoped storage
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
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