Last active
October 18, 2018 10:07
-
-
Save miladd3/a40e5dca29dbe4b8cdfe65d959c92b2d to your computer and use it in GitHub Desktop.
Get and set storage easily
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
/** | |
* get local storage item and return parsed object or array | |
* | |
* @param name | |
* @returns {any} | |
*/ | |
function getStorage(name) { | |
try { | |
if (localStorage.getItem(name)) { | |
return JSON.parse(localStorage.getItem(name)); | |
} | |
} catch (e) { | |
console.error(e); | |
} | |
} | |
/** | |
* set variable to storage easily without thinking of stratifying it | |
* | |
* @param {string} name | |
* @param data | |
* @returns {{name: *, data: *}} | |
*/ | |
function setStorage(name,data) { | |
try { | |
let dataString; | |
if(typeof data == 'string') { | |
dataString = data; | |
}else { | |
dataString = JSON.stringify(data); | |
} | |
localStorage.setItem(name,dataString); | |
return { | |
name, | |
data | |
} | |
}catch (e) { | |
console.error(e) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment