local-storage.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. import { debugConsole } from '@/utils/debugging'
  6. /**
  7. * Catch, log and otherwise ignore errors.
  8. *
  9. * @param {function} fn localStorage function to call
  10. * @param {string?} key Key passed to the localStorage function (if any)
  11. * @param {any?} value Value passed to the localStorage function (if any)
  12. */
  13. const callSafe = function (fn, key, value) {
  14. try {
  15. return fn(key, value)
  16. } catch (e) {
  17. debugConsole.error('localStorage exception', e)
  18. return null
  19. }
  20. }
  21. const getItem = function (key) {
  22. return JSON.parse(localStorage.getItem(key))
  23. }
  24. const setItem = function (key, value) {
  25. localStorage.setItem(key, JSON.stringify(value))
  26. }
  27. const clear = function () {
  28. localStorage.clear()
  29. }
  30. const removeItem = function (key) {
  31. return localStorage.removeItem(key)
  32. }
  33. const customLocalStorage = {
  34. getItem: key => callSafe(getItem, key),
  35. setItem: (key, value) => callSafe(setItem, key, value),
  36. clear: () => callSafe(clear),
  37. removeItem: key => callSafe(removeItem, key),
  38. }
  39. export default customLocalStorage