react-use
Version:
Collection of React Hooks
40 lines (39 loc) • 1.52 kB
JavaScript
import { useEffect, useState } from 'react';
import { isBrowser } from './misc/util';
var useSessionStorage = function (key, initialValue, raw) {
if (!isBrowser) {
return [initialValue, function () { }];
}
// eslint-disable-next-line react-hooks/rules-of-hooks
var _a = 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
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];
};
export default useSessionStorage;