local-storage.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. /**
  2. * localStorage can throw browser exceptions, for example if it is full We don't
  3. * use localStorage for anything critical, so in that case just fail gracefully.
  4. */
  5. /**
  6. * Catch, log and otherwise ignore errors.
  7. *
  8. * @param {function} fn localStorage function to call
  9. * @param {string?} key Key passed to the localStorage function (if any)
  10. * @param {any?} value Value passed to the localStorage function (if any)
  11. */
  12. const callSafe = function (fn, key, value) {
  13. try {
  14. return fn(key, value)
  15. } catch (e) {
  16. console.error('localStorage exception', e)
  17. return null
  18. }
  19. }
  20. const getItem = function (key) {
  21. return JSON.parse(localStorage.getItem(key))
  22. }
  23. const setItem = function (key, value) {
  24. localStorage.setItem(key, JSON.stringify(value))
  25. }
  26. const clear = function () {
  27. localStorage.clear()
  28. }
  29. const removeItem = function (key) {
  30. return localStorage.removeItem(key)
  31. }
  32. const customLocalStorage = {
  33. getItem: key => callSafe(getItem, key),
  34. setItem: (key, value) => callSafe(setItem, key, value),
  35. clear: () => callSafe(clear),
  36. removeItem: key => callSafe(removeItem, key),
  37. }
  38. export default customLocalStorage