Skip to content

Instantly share code, notes, and snippets.

@davidgilbertson
Last active April 17, 2020 01:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidgilbertson/227671a8c6a35cae4c6cebaaa5803dd4 to your computer and use it in GitHub Desktop.
Save davidgilbertson/227671a8c6a35cae4c6cebaaa5803dd4 to your computer and use it in GitHub Desktop.
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