42 lines
1.6 KiB
JavaScript
42 lines
1.6 KiB
JavaScript
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
var react_1 = require("react");
|
|
var util_1 = require("./misc/util");
|
|
var useSessionStorage = function (key, initialValue, raw) {
|
|
if (!util_1.isBrowser) {
|
|
return [initialValue, function () { }];
|
|
}
|
|
// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
var _a = react_1.useState(function () {
|
|
try {
|
|
var sessionStorageValue = sessionStorage.getItem(key);
|
|
if (typeof sessionStorageValue !== 'string') {
|
|
sessionStorage.setItem(key, raw ? String(initialValue) : JSON.stringify(initialValue));
|
|
return initialValue;
|
|
}
|
|
else {
|
|
return raw ? sessionStorageValue : JSON.parse(sessionStorageValue || 'null');
|
|
}
|
|
}
|
|
catch (_a) {
|
|
// If user is in private mode or has storage restriction
|
|
// sessionStorage can throw. JSON.parse and JSON.stringify
|
|
// can throw, too.
|
|
return initialValue;
|
|
}
|
|
}), state = _a[0], setState = _a[1];
|
|
// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
react_1.useEffect(function () {
|
|
try {
|
|
var serializedState = raw ? String(state) : JSON.stringify(state);
|
|
sessionStorage.setItem(key, serializedState);
|
|
}
|
|
catch (_a) {
|
|
// If user is in private mode or has storage restriction
|
|
// sessionStorage can throw. Also JSON.stringify can throw.
|
|
}
|
|
});
|
|
return [state, setState];
|
|
};
|
|
exports.default = useSessionStorage;
|