2020-09-18 06:04:31 -04:00
|
|
|
/**
|
|
|
|
* localStorage can throw browser exceptions, for example if it is full We don't
|
|
|
|
* use localStorage for anything critical, so in that case just fail gracefully.
|
|
|
|
*/
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Catch, log and otherwise ignore errors.
|
|
|
|
*
|
|
|
|
* @param {function} fn localStorage function to call
|
|
|
|
* @param {string?} key Key passed to the localStorage function (if any)
|
|
|
|
* @param {any?} value Value passed to the localStorage function (if any)
|
|
|
|
*/
|
2021-04-14 09:17:21 -04:00
|
|
|
const callSafe = function (fn, key, value) {
|
2020-09-18 06:04:31 -04:00
|
|
|
try {
|
|
|
|
return fn(key, value)
|
|
|
|
} catch (e) {
|
|
|
|
console.error('localStorage exception', e)
|
|
|
|
return null
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-04-14 09:17:21 -04:00
|
|
|
const getItem = function (key) {
|
2020-09-18 06:04:31 -04:00
|
|
|
return JSON.parse(localStorage.getItem(key))
|
|
|
|
}
|
|
|
|
|
2021-04-14 09:17:21 -04:00
|
|
|
const setItem = function (key, value) {
|
2020-09-18 06:04:31 -04:00
|
|
|
localStorage.setItem(key, JSON.stringify(value))
|
|
|
|
}
|
|
|
|
|
2021-04-14 09:17:21 -04:00
|
|
|
const clear = function () {
|
2020-09-18 06:04:31 -04:00
|
|
|
localStorage.clear()
|
|
|
|
}
|
|
|
|
|
2021-04-14 09:17:21 -04:00
|
|
|
const removeItem = function (key) {
|
2020-09-18 06:04:31 -04:00
|
|
|
return localStorage.removeItem(key)
|
|
|
|
}
|
|
|
|
|
|
|
|
const customLocalStorage = {
|
|
|
|
getItem: key => callSafe(getItem, key),
|
|
|
|
setItem: (key, value) => callSafe(setItem, key, value),
|
|
|
|
clear: () => callSafe(clear),
|
2021-04-27 03:52:58 -04:00
|
|
|
removeItem: key => callSafe(removeItem, key),
|
2020-09-18 06:04:31 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
export default customLocalStorage
|