mirror of
https://github.com/streamich/react-use.git
synced 2026-01-25 14:17:16 +00:00
More DRY code. Also move non-hooks to separate directories. BREAKING CHANGE: all `create*` factories been moved to `factory` subdirectory and in case direct import should be imported like `react-use/esm/factory/createBreakpoint` BREAKING CHANGE: `comps` directory renamed to `component`
42 lines
1.3 KiB
TypeScript
42 lines
1.3 KiB
TypeScript
import { useEffect, useState } from 'react';
|
|
import { isBrowser } from './misc/util';
|
|
|
|
const useSessionStorage = <T>(key: string, initialValue?: T, raw?: boolean): [T, (value: T) => void] => {
|
|
if (!isBrowser) {
|
|
return [initialValue as T, () => {}];
|
|
}
|
|
|
|
// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
const [state, setState] = useState<T>(() => {
|
|
try {
|
|
const 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 {
|
|
// If user is in private mode or has storage restriction
|
|
// sessionStorage can throw. JSON.parse and JSON.stringify
|
|
// cat throw, too.
|
|
return initialValue;
|
|
}
|
|
});
|
|
|
|
// eslint-disable-next-line react-hooks/rules-of-hooks
|
|
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.
|
|
}
|
|
});
|
|
|
|
return [state, setState];
|
|
};
|
|
|
|
export default useSessionStorage;
|