@plq/use-persisted-state
Version:
useState hook with persistence in storage
48 lines • 1.92 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = default_1;
const react_1 = require("react");
const is_1 = require("@plq/is");
function getValue(key, value) {
let newState = null;
try {
newState = JSON.parse(value);
}
catch (err) {
console.error('use-persisted-state: Can\'t parse value from storage', err);
}
return newState && key in newState ? newState[key] : null;
}
function useStorageHandler(itemKey, storageKey, setState, initialValue) {
return (changes) => {
Object.entries(changes).forEach(([key, change]) => {
if (key === storageKey
&& (change.newValue === null || change.newValue === undefined)
&& change.oldValue !== null
&& change.oldValue !== undefined) {
const oldValue = getValue(itemKey, change.oldValue);
if (oldValue !== initialValue)
setState((0, is_1.isFunction)(initialValue) ? initialValue() : initialValue);
}
if (key === storageKey
&& change.newValue !== null
&& change.newValue !== undefined) {
const newValue = getValue(itemKey, change.newValue);
if (newValue !== null)
setState(newValue);
}
});
};
}
function default_1(key, storageKey, setState, storage, initialValue) {
(0, react_1.useEffect)(() => {
const handleStorage = useStorageHandler(key, storageKey, setState, initialValue);
storage.onChanged.addListener(handleStorage);
return () => {
if (storage.onChanged.hasListener(handleStorage)) {
storage.onChanged.removeListener(handleStorage);
}
};
}, [initialValue, key, storage.onChanged, storageKey, setState]);
}
//# sourceMappingURL=use-storage-handler.js.map