@darwish/hooks-core
Version:
30 lines (29 loc) • 1.1 kB
JavaScript
import { isFunction, isString } from "@darwish/utils-is";
import { useState } from "react";
export default function useStorage(type, key, defaultValue) {
var _a = useState(function () {
var _a, _b;
if (typeof window === "undefined")
return undefined;
try {
return window[type].getItem(key) === null
? defaultValue
: (_a = JSON.parse(window[type].getItem(key))) !== null && _a !== void 0 ? _a : defaultValue;
}
catch (_c) {
return (_b = window[type].getItem(key)) !== null && _b !== void 0 ? _b : defaultValue;
}
}), storage = _a[0], setStorage = _a[1];
var updateStorage = function (value) {
value = isFunction(value) ? value(storage) : value;
window[type].setItem(key, isString(value) ? value : JSON.stringify(value));
setStorage(value);
};
var removeStorage = function () {
window[type].removeItem(key);
if (storage) {
setStorage(undefined);
}
};
return [storage, updateStorage, removeStorage];
}