Skip to content

Instantly share code, notes, and snippets.

@ungarson
Created October 10, 2021 13:55
Show Gist options
  • Select an option

  • Save ungarson/a63a78d8a72c479f946e4a226f5e51c0 to your computer and use it in GitHub Desktop.

Select an option

Save ungarson/a63a78d8a72c479f946e4a226f5e51c0 to your computer and use it in GitHub Desktop.

Revisions

  1. ungarson created this gist Oct 10, 2021.
    30 changes: 30 additions & 0 deletions Storage.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    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);
    }
    }