Last active
April 17, 2020 01:41
-
-
Save davidgilbertson/227671a8c6a35cae4c6cebaaa5803dd4 to your computer and use it in GitHub Desktop.
This file contains 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
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; | |
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; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment