Created
March 21, 2020 00:36
-
-
Save jwrigh26/82b71da5b5994112f816a3b4e86babc5 to your computer and use it in GitHub Desktop.
Local & Session Storage Helper
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 characters
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