@ohm-vision/react-storage
Version:
Extension to React to interact with native Window Storage object
108 lines (107 loc) • 3.49 kB
JavaScript
import { useEffect, useMemo, useState } from "react";
var EMPTY = "";
/**
* Default storage hook, this method is what all other `use{type}Storage` methods derive from
*
* This hook will default to `JSON.parse` and `JSON.stringify` to convert methods
* @param props
* @returns
*/
export function useStorage(props) {
var storageType = props.storageType, key = props.key, convert = props.convert, defaultValue = props.defaultValue, syncData = props.syncData;
if (!Boolean(storageType))
storageType = "session";
if (storageType !== "session" && storageType !== "local")
throw new Error("Invalid storageType specified");
if (!key)
throw new Error("Unable to initialize stateful storage without key");
if (!convert) {
convert = {
fromStorage: JSON.parse,
toStorage: JSON.stringify
};
}
var fromStorage = convert.fromStorage, toStorage = convert.toStorage;
if (!fromStorage)
throw new Error("No fromStorage specified in convert");
if (!toStorage)
throw new Error("No toStorage specified in convert");
// const isBrowser: boolean = IsBrowser();
var storageApi = useMemo(function () { return window["".concat(storageType, "Storage")]; }, [storageType]);
/// internals
function getItemInternal() {
return storageApi === null || storageApi === void 0 ? void 0 : storageApi.getItem(key);
}
function setItemInternal(value) {
storageApi === null || storageApi === void 0 ? void 0 : storageApi.setItem(key, value);
}
function removeItemInternal() {
storageApi === null || storageApi === void 0 ? void 0 : storageApi.removeItem(key);
}
var _a = useState(getItem), storedValue = _a[0], setStoredValue = _a[1];
// attach event listeners
useEffect(function () {
function onStorage(e) {
if (e.key === key) {
setValue(e.newValue);
}
}
if (syncData !== false) {
window.addEventListener("storage", onStorage, false);
return function () { return window.removeEventListener("storage", onStorage, false); };
}
}, [syncData, key]);
function setValue(str) {
if (str !== storedValue.str) {
var obj = strToObj(str);
setStoredValue({
obj: obj,
str: str
});
}
}
function setItem(value) {
var str = objToStr(value);
setValue(str);
if (isEmpty(str)) {
removeItemInternal();
}
else {
setItemInternal(str);
}
}
function removeItem() {
setItem(null);
}
function getItem() {
var str = getItemInternal() || EMPTY;
var obj = strToObj(str);
return {
obj: obj,
str: str,
};
}
function isEmpty(str) {
return str === EMPTY;
}
function isDefault(obj) {
return obj == null || obj === defaultValue;
}
function objToStr(obj) {
var str;
if (isDefault(obj))
str = EMPTY;
else
str = toStorage(obj);
return str;
}
function strToObj(str) {
var obj;
if (isEmpty(str))
obj = defaultValue;
else
obj = fromStorage(str);
return obj;
}
return [storedValue === null || storedValue === void 0 ? void 0 : storedValue.obj, setItem, removeItem];
}