Skip to content

Instantly share code, notes, and snippets.

@davidgilbertson
Last active April 17, 2020 01:41
Show Gist options
  • Select an option

  • Save davidgilbertson/227671a8c6a35cae4c6cebaaa5803dd4 to your computer and use it in GitHub Desktop.

Select an option

Save davidgilbertson/227671a8c6a35cae4c6cebaaa5803dd4 to your computer and use it in GitHub Desktop.

Revisions

  1. davidgilbertson revised this gist Apr 17, 2020. 1 changed file with 16 additions and 10 deletions.
    26 changes: 16 additions & 10 deletions storage.ts
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,20 @@
    const hasLocalStorage = typeof window !== 'undefined' && !!window.localStorage;

    export const set = (key: string, data: any) => {
    if (!hasLocalStorage) return undefined;

    try {
    const string = typeof data === 'string' ? data : JSON.stringify(data);

    return localStorage.setItem(key, string);
    } catch (err) {
    return undefined;
    }
    };

    export const get = (key: string) => {
    if (!hasLocalStorage) return undefined;

    const data = localStorage.getItem(key);
    if (!data) return data;

    @@ -10,13 +26,3 @@ export const get = (key: string) => {
    return data;
    }
    };

    export const set = (key: string, data: any) => {
    try {
    const string = typeof data === 'string' ? data : JSON.stringify(data);

    return localStorage.setItem(key, string);
    } catch (err) {
    return undefined;
    }
    };
  2. davidgilbertson created this gist Apr 17, 2020.
    22 changes: 22 additions & 0 deletions storage.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,22 @@
    export const get = (key: string) => {
    const data = localStorage.getItem(key);
    if (!data) return data;

    try {
    return JSON.parse(data);
    } catch (err) {
    // So we return whatever we've got on a failure
    // E.g. the data could be a plain string, which errors on JSON.parse.
    return data;
    }
    };

    export const set = (key: string, data: any) => {
    try {
    const string = typeof data === 'string' ? data : JSON.stringify(data);

    return localStorage.setItem(key, string);
    } catch (err) {
    return undefined;
    }
    };