package.cjs.react-utils.useLocalStorage.useLocalStorage.js Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of neeto-commons-frontend Show documentation
Show all versions of neeto-commons-frontend Show documentation
A package encapsulating common code across neeto projects including initializers, utility functions, common components and hooks and so on.
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _react = require("react");
var _ramda = require("ramda");
var _utils = require("../../utils");
/* eslint-disable @bigbinary/neeto/no-local-storage */
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 = (0, _react.useState)(function () {
return getStorageValue(key, defaultValue);
}),
_useState2 = (0, _slicedToArray2["default"])(_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 ((0, _ramda.isNil)(newValue)) {
(0, _utils.removeFromLocalStorage)(key);
} else {
(0, _utils.setToLocalStorage)(key, newValue);
}
return newValue;
});
};
return [storedValue, setValue];
};
var _default = useLocalStorage;
exports["default"] = _default;
//# sourceMappingURL=useLocalStorage.js.map