@startpage/local-storage
Version:
Local storage management for your startpage
30 lines (29 loc) • 1.25 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useStorage = void 0;
const react_1 = require("react");
const parseStorageItem_1 = require("../fragments/parseStorageItem");
const StoragePrefixProvider_1 = require("../StoragePrefix/StoragePrefixProvider");
const isCallable = (value) => typeof value === "function";
const STORAGE = window.localStorage;
const initiateStorage = (key, initialValue) => {
const value = (0, parseStorageItem_1.parseStorageItem)(key);
if (value === null) {
STORAGE.setItem(key, JSON.stringify(initialValue));
return initialValue;
}
return value;
};
const useStorage = (key, initialValue) => {
const prefix = (0, StoragePrefixProvider_1.useStoragePrefix)();
const [value, setValue] = (0, react_1.useState)(initiateStorage(prefix + key, initialValue));
const setStorage = (0, react_1.useCallback)(value => {
setValue(previous => {
const newValue = isCallable(value) ? value(previous) : value;
STORAGE.setItem(prefix + key, JSON.stringify(newValue));
return newValue;
});
}, [prefix, key]);
return [value, setStorage];
};
exports.useStorage = useStorage;