Skip to content

Instantly share code, notes, and snippets.

@jwrigh26
Created March 21, 2020 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwrigh26/82b71da5b5994112f816a3b4e86babc5 to your computer and use it in GitHub Desktop.
Save jwrigh26/82b71da5b5994112f816a3b4e86babc5 to your computer and use it in GitHub Desktop.
Local & Session Storage Helper
export default function storage(isSession = false) {
const manager = isSession ? sessionStorage : localStorage;
const hasManager = isSession ? window.sessionStorage : window.localStorage;
function getItem(id, json = true) {
if (hasManager) {
return json ? JSON.parse(manager.getItem(id)) : manager.getItem(id);
}
return undefined;
}
function setItem(id, data, json = true) {
if (hasManager && json) {
manager.setItem(id, JSON.stringify(data));
return;
}
if (hasManager && !json) {
manager.setItem(id, data);
return;
}
}
function clear() {
if (hasManager) {
manager.clear();
}
}
function removeItem(id) {
if (hasManager) {
manager.removeItem(id);
}
}
return {
clear,
getItem,
removeItem,
setItem,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment