All files / app/platform usePersistedState.ts

94.73% Statements 18/19
62.5% Branches 5/8
100% Functions 4/4
94.73% Lines 18/19

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 4368x       68x       68x             2076x 2076x     2076x   78x     78x 78x 78x 78x       2076x 4x 4x 4x   2076x     68x 3x    
import { useCallback, useState } from "react";
import {
  sendState,
  clearState as nativeLinkClearState,
} from "platform/nativeLink";
 
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();
}