All Downloads are FREE. Search and download functionalities are using the official Maven repository.

package.react-utils.useLocalStorage.useLocalStorage.js Maven / Gradle / Ivy

Go to download

A package encapsulating common code across neeto projects including initializers, utility functions, common components and hooks and so on.

There is a newer version: 4.12.3
Show newest version
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
/* eslint-disable @bigbinary/neeto/no-local-storage */

import { useState } from "react";
import { isNil } from "ramda";
import { removeFromLocalStorage, setToLocalStorage } from "../../utils";
var getStorageValue = function getStorageValue(key, defaultValue) {
  try {
    var storedValue = localStorage.getItem(key);
    return storedValue ? JSON.parse(storedValue) : defaultValue;
  } catch (error) {
    logger.error(error);
    return defaultValue;
  }
};
var useLocalStorage = function useLocalStorage(key, defaultValue) {
  var _useState = useState(function () {
      return getStorageValue(key, defaultValue);
    }),
    _useState2 = _slicedToArray(_useState, 2),
    storedValue = _useState2[0],
    setStoredValue = _useState2[1];
  var setValue = function setValue(value) {
    return setStoredValue(function (prevStoredValue) {
      var newValue = typeof value === "function" ? value(prevStoredValue) : value;
      if (isNil(newValue)) {
        removeFromLocalStorage(key);
      } else {
        setToLocalStorage(key, newValue);
      }
      return newValue;
    });
  };
  return [storedValue, setValue];
};
export default useLocalStorage;
//# sourceMappingURL=useLocalStorage.js.map




© 2015 - 2024 Weber Informatics LLC | Privacy Policy