Skip to content

Instantly share code, notes, and snippets.

@ungarson
Created October 10, 2021 13:55
Show Gist options
  • Save ungarson/a63a78d8a72c479f946e4a226f5e51c0 to your computer and use it in GitHub Desktop.
Save ungarson/a63a78d8a72c479f946e4a226f5e51c0 to your computer and use it in GitHub Desktop.
Storage class for local storage management
export default class Storage {
static get(key) {
const value = localStorage.getItem(key);
if (!value) return undefined;
try {
return JSON.parse(value);
} catch {
localStorage.removeItem(key);
return undefined;
}
}
static set(key, value, firstTry = true) {
try {
localStorage.setItem(key, JSON.stringify(value));
} catch {
if (firstTry) {
Object.keys(localStorage)
.filter((x) => x.startsWith('tz') || x.startsWith('KT'))
.forEach((x) => localStorage.removeItem(x));
this.set(key, value, false);
}
}
}
static remove(key) {
localStorage.removeItem(key);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment