Created
October 10, 2021 13:55
-
-
Save ungarson/a63a78d8a72c479f946e4a226f5e51c0 to your computer and use it in GitHub Desktop.
Storage class for local storage management
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
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