1 | "use strict";
|
---|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
3 | var react_1 = require("react");
|
---|
4 | var util_1 = require("./misc/util");
|
---|
5 | var useSessionStorage = function (key, initialValue, raw) {
|
---|
6 | if (!util_1.isBrowser) {
|
---|
7 | return [initialValue, function () { }];
|
---|
8 | }
|
---|
9 | // eslint-disable-next-line react-hooks/rules-of-hooks
|
---|
10 | var _a = react_1.useState(function () {
|
---|
11 | try {
|
---|
12 | var sessionStorageValue = sessionStorage.getItem(key);
|
---|
13 | if (typeof sessionStorageValue !== 'string') {
|
---|
14 | sessionStorage.setItem(key, raw ? String(initialValue) : JSON.stringify(initialValue));
|
---|
15 | return initialValue;
|
---|
16 | }
|
---|
17 | else {
|
---|
18 | return raw ? sessionStorageValue : JSON.parse(sessionStorageValue || 'null');
|
---|
19 | }
|
---|
20 | }
|
---|
21 | catch (_a) {
|
---|
22 | // If user is in private mode or has storage restriction
|
---|
23 | // sessionStorage can throw. JSON.parse and JSON.stringify
|
---|
24 | // can throw, too.
|
---|
25 | return initialValue;
|
---|
26 | }
|
---|
27 | }), state = _a[0], setState = _a[1];
|
---|
28 | // eslint-disable-next-line react-hooks/rules-of-hooks
|
---|
29 | react_1.useEffect(function () {
|
---|
30 | try {
|
---|
31 | var serializedState = raw ? String(state) : JSON.stringify(state);
|
---|
32 | sessionStorage.setItem(key, serializedState);
|
---|
33 | }
|
---|
34 | catch (_a) {
|
---|
35 | // If user is in private mode or has storage restriction
|
---|
36 | // sessionStorage can throw. Also JSON.stringify can throw.
|
---|
37 | }
|
---|
38 | });
|
---|
39 | return [state, setState];
|
---|
40 | };
|
---|
41 | exports.default = useSessionStorage;
|
---|