Created
September 5, 2022 21:42
-
-
Save Antrikshy/41ab89840f367c1ae900a319e1bb63e7 to your computer and use it in GitHub Desktop.
A painless localStorage manager in JS ES6, with support for partitioning keys so that different parts of a project don't step on each other's toes
This file contains 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
/* | |
If you're viewing this on GitHub Gist, see a full guide, including React Router examples at: | |
https://antrikshy.com/code/painless-partitioned-localstorage-with-namespaces-react-router | |
*/ | |
export default class PersistenceHandler { | |
constructor(prefix="Project-Name") { | |
this.prefix = prefix; | |
} | |
constructKey(subKey) { | |
return `${this.prefix}-${subKey}`; | |
} | |
write(subKey, payload) { | |
const payloadString = JSON.stringify(payload); | |
localStorage.setItem(this.constructKey(subKey), payloadString); | |
} | |
read(subKey) { | |
const payloadString = localStorage.getItem(this.constructKey(subKey)); | |
return JSON.parse(payloadString); | |
} | |
remove(subKey) { | |
localStorage.removeItem(this.constructKey(subKey)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment