1
0
mirror of https://github.com/checktheroads/hyperglass synced 2024-05-11 05:55:08 +00:00
Files
checktheroads-hyperglass/hyperglass/ui/hooks/useSessionStorage.js

43 lines
1.3 KiB
JavaScript
Raw Normal View History

2020-04-16 00:26:23 -07:00
/*
react-use: useSessionStorage
https://github.com/streamich/react-use/blob/master/src/useSessionStorage.ts
*/
2020-10-07 09:41:58 -07:00
import { useEffect, useState } from 'react';
2020-04-16 00:26:23 -07:00
export const useSessionStorage = (key, initialValue, raw) => {
2020-10-07 09:41:58 -07:00
const isClient = typeof window === 'object';
if (!isClient) {
return [initialValue, () => {}];
}
2020-04-16 00:26:23 -07:00
const [state, setState] = useState(() => {
try {
const sessionStorageValue = sessionStorage.getItem(key);
2020-10-07 09:41:58 -07:00
if (typeof sessionStorageValue !== 'string') {
sessionStorage.setItem(key, raw ? String(initialValue) : JSON.stringify(initialValue));
return initialValue;
} else {
2020-10-07 09:41:58 -07:00
return raw ? sessionStorageValue : JSON.parse(sessionStorageValue || 'null');
}
} catch {
// If user is in private mode or has storage restriction
// sessionStorage can throw. JSON.parse and JSON.stringify
// cat throw, too.
return initialValue;
}
});
2020-04-16 00:26:23 -07:00
useEffect(() => {
try {
const serializedState = raw ? String(state) : JSON.stringify(state);
sessionStorage.setItem(key, serializedState);
} catch {
// If user is in private mode or has storage restriction
// sessionStorage can throw. Also JSON.stringify can throw.
}
});
2020-04-16 00:26:23 -07:00
return [state, setState];
2020-04-16 00:26:23 -07:00
};