Last active
May 2, 2017 11:59
-
-
Save GianlucaGuarini/95494d3fd821a1b8a460dd7dba01d5c6 to your computer and use it in GitHub Desktop.
A simple script to deal safely with the localStorage
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
/** | |
* Deal with the localStorage avoiding odd issues due to paranoids that have disabled it by default | |
*/ | |
const ls = window.localStorage | |
/** | |
* Call any method on the localStorage avoiding to throw errors | |
* @param {string} method - method we want to call | |
* @param {array} args - serialized params that will be proxied to the method we are going to call | |
* @returns {null|string} whatever the method call will return | |
*/ | |
function tryOrFailSilently(method, ...args) { | |
try { | |
return ls[method].apply(ls, args) | |
} catch (e) { | |
console && console.error && console.error(e) | |
return null | |
} | |
} | |
/** | |
* Simple object to read get and clear from the localStorage | |
*/ | |
export default { | |
set(item, value) { | |
return tryOrFailSilently('setItem', item, value) | |
}, | |
get(item) { | |
return tryOrFailSilently('getItem', item) | |
}, | |
clear() { | |
return tryOrFailSilently('clear') | |
}, | |
remove(item) { | |
return tryOrFailSilently('removeItem', item) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment