Skip to content

Instantly share code, notes, and snippets.

@Antrikshy
Created September 5, 2022 21:42
Show Gist options
  • Save Antrikshy/41ab89840f367c1ae900a319e1bb63e7 to your computer and use it in GitHub Desktop.
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
/*
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