package.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.
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