Skip to content

Instantly share code, notes, and snippets.

@GianlucaGuarini
Last active May 2, 2017 11:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save GianlucaGuarini/95494d3fd821a1b8a460dd7dba01d5c6 to your computer and use it in GitHub Desktop.
Save GianlucaGuarini/95494d3fd821a1b8a460dd7dba01d5c6 to your computer and use it in GitHub Desktop.
A simple script to deal safely with the localStorage
/**
* 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