export function useURLState()

in src/hooks/usePagination/index.ts [101:154]


export function useURLState(
  key: string,
  defaultValue: number
): [number, React.Dispatch<React.SetStateAction<number>>];
export function useURLState(
  key: string,
  valueOrParams: number | URLStateParams<number>
): [number, React.Dispatch<React.SetStateAction<number>>];
/**
 * A hook to manage a state variable that is also stored in the URL.
 *
 * @param key The name of the key in the URL. If empty, then the hook behaves like useState.
 * @param paramsOrDefault The default value of the state variable, or the params object.
 *
 */
export function useURLState<T extends string | number | undefined = string>(
  key: string,
  paramsOrDefault: T | URLStateParams<T>
): [T, React.Dispatch<React.SetStateAction<T>>] {
  const params: URLStateParams<T> =
    typeof paramsOrDefault === 'object' ? paramsOrDefault : { defaultValue: paramsOrDefault };
  const { defaultValue, hideDefault = true, prefix = '' } = params;
  const history = useHistory();
  // Don't even use the prefix if the key is empty
  const fullKey = getFullKey(key, prefix);

  const initialValue = React.useMemo(() => {
    const newValue = getURLValue(fullKey, defaultValue, history);
    if (newValue === null) {
      return defaultValue;
    }
    return newValue;
  }, [defaultValue, fullKey, history]);
  const [value, setValue] = React.useState<T>(initialValue as T);

  React.useEffect(
    () => {
      updateValue(fullKey, defaultValue, value, setValue);
    },
    // eslint-disable-next-line
    [history]
  );

  React.useEffect(() => {
    // An empty key means that we don't want to use the state from the URL.
    if (fullKey === '') {
      return;
    }

    updateParams(fullKey, defaultValue, value, hideDefault, history);
  }, [defaultValue, fullKey, hideDefault, history, value]);

  return [value, setValue] as [T, React.Dispatch<React.SetStateAction<T>>];
}