All files / app/platform usePersistedState.ts

92.3% Statements 24/26
70% Branches 7/10
100% Functions 6/6
92.3% Lines 24/26

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 54119x 119x       218x           3564x 3564x   2961x 2961x       2961x   3564x   205x     205x 205x 205x 205x       3564x 9x 9x 9x   3564x             3346x 3346x 3346x     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();
}