main
Last change
on this file was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago |
Update repo after prototype presentation
|
-
Property mode
set to
100644
|
File size:
1.5 KB
|
Rev | Line | |
---|
[d565449] | 1 | import { useEffect, useState } from 'react';
|
---|
| 2 | import { isBrowser } from './misc/util';
|
---|
| 3 | var useSessionStorage = function (key, initialValue, raw) {
|
---|
| 4 | if (!isBrowser) {
|
---|
| 5 | return [initialValue, function () { }];
|
---|
| 6 | }
|
---|
| 7 | // eslint-disable-next-line react-hooks/rules-of-hooks
|
---|
| 8 | var _a = useState(function () {
|
---|
| 9 | try {
|
---|
| 10 | var sessionStorageValue = sessionStorage.getItem(key);
|
---|
| 11 | if (typeof sessionStorageValue !== 'string') {
|
---|
| 12 | sessionStorage.setItem(key, raw ? String(initialValue) : JSON.stringify(initialValue));
|
---|
| 13 | return initialValue;
|
---|
| 14 | }
|
---|
| 15 | else {
|
---|
| 16 | return raw ? sessionStorageValue : JSON.parse(sessionStorageValue || 'null');
|
---|
| 17 | }
|
---|
| 18 | }
|
---|
| 19 | catch (_a) {
|
---|
| 20 | // If user is in private mode or has storage restriction
|
---|
| 21 | // sessionStorage can throw. JSON.parse and JSON.stringify
|
---|
| 22 | // can throw, too.
|
---|
| 23 | return initialValue;
|
---|
| 24 | }
|
---|
| 25 | }), state = _a[0], setState = _a[1];
|
---|
| 26 | // eslint-disable-next-line react-hooks/rules-of-hooks
|
---|
| 27 | useEffect(function () {
|
---|
| 28 | try {
|
---|
| 29 | var serializedState = raw ? String(state) : JSON.stringify(state);
|
---|
| 30 | sessionStorage.setItem(key, serializedState);
|
---|
| 31 | }
|
---|
| 32 | catch (_a) {
|
---|
| 33 | // If user is in private mode or has storage restriction
|
---|
| 34 | // sessionStorage can throw. Also JSON.stringify can throw.
|
---|
| 35 | }
|
---|
| 36 | });
|
---|
| 37 | return [state, setState];
|
---|
| 38 | };
|
---|
| 39 | export default useSessionStorage;
|
---|
Note:
See
TracBrowser
for help on using the repository browser.