react-use
Version:
Collection of React Hooks
38 lines (37 loc) • 1.4 kB
JavaScript
import { useEffect, useState } from 'react';
import { isClient } from './util';
var useSessionStorage = function (key, initialValue, raw) {
if (!isClient) {
return [initialValue, function () { }];
}
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
// cat throw, too.
return initialValue;
}
}), state = _a[0], setState = _a[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];
};
export default useSessionStorage;