Last active
April 17, 2020 01:41
-
-
Save davidgilbertson/227671a8c6a35cae4c6cebaaa5803dd4 to your computer and use it in GitHub Desktop.
Revisions
-
davidgilbertson revised this gist
Apr 17, 2020 . 1 changed file with 16 additions and 10 deletions.There are no files selected for viewing
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 charactersOriginal 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; } }; -
davidgilbertson created this gist
Apr 17, 2020 .There are no files selected for viewing
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 charactersOriginal 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; } };