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 | 77x 77x 1885x 1885x 1885x 1885x 70x 70x 70x 70x 70x 1885x 4x 4x 4x 1885x 3x 3x | import { clearState as nativeLinkClearState, sendState, } from "platform/nativeLink"; import { useCallback, useState } from "react"; type StorageType = "localStorage" | "sessionStorage"; export function usePersistedState<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>( saved !== null ? JSON.parse(saved) : defaultValue ); 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]; } export function clearStorage() { window.sessionStorage.clear(); } |