Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | 100x 100x 216x 3000x 3000x 2442x 2442x 2442x 3000x 204x 204x 204x 204x 204x 3000x 9x 9x 9x 3000x 2784x 2784x 2784x 3x 3x | import { useCallback, useState } from "react";
import {
clearState as nativeLinkClearState,
sendState,
} from "utils/nativeLink";
type StorageType = "localStorage" | "sessionStorage";
export function useClearablePersistedState<T>(
key: string,
defaultValue: T,
storage: StorageType = "localStorage",
): [T | undefined, (value: T) => void, () => void] {
// in ssr, window doesn't exist, just use default
const saved =
typeof window !== "undefined" ? window[storage].getItem(key) : null;
const [_state, _setState] = useState<T | undefined>(() => {
let initialValue: T | undefined;
try {
initialValue = saved !== null ? JSON.parse(saved) : defaultValue;
} catch {
initialValue = defaultValue;
}
return initialValue;
});
const setState = useCallback(
(value: T) => {
Iif (value === undefined) {
console.warn(`${key} can't be stored as undefined, casting to null.`);
}
const v = value === undefined ? null : value;
window[storage].setItem(key, JSON.stringify(v));
sendState(key, v);
_setState(value);
},
[key, storage],
);
const clearState = useCallback(() => {
window[storage].removeItem(key);
nativeLinkClearState(key);
_setState(undefined);
}, [key, storage]);
return [_state, setState, clearState];
}
/**
* @todo Consolidate all usage to this hook eventually - the clearable version should be doable via this hook only so the
* state has stronger typing and doesn't need to be type casted.
*/
export function usePersistedState<T>(
key: string,
defaultValue: T,
storage: StorageType = "localStorage",
) {
const [state, setState] = useClearablePersistedState(
key,
defaultValue,
storage,
);
return [state as T, setState] as const;
}
export function clearStorage() {
window.sessionStorage.clear();
}
|