pbeshai / use-query-params

React Hook for managing state in URL query parameters with easy serialization.

Home Page:https://pbeshai.github.io/use-query-params

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

useQueryParam - unset url param if new value is default

d9k opened this issue · comments

I want to unset url param if new value is default. Couldn't achieve this behavior using withDefault().

Eventually I wrote my own hook which wraps useQueryParam() but I need help with typescript typings:

const useQueryParamDefault = <D, D2 = D>(
  name: string,
  paramConfig: QueryParamConfig<D, D2> = StringParam as QueryParamConfig<any>,
  defaultValue: NonNullable<D2>
): [NonNullable<D2>, (newValue: NewValueType<D>, updateType?: UrlUpdateType) => void] => {
  const [valueRaw, setValueRaw] = useQueryParam<D, D2>(name, paramConfig);

  // TODO type fix?
  const value: NonNullable<D2> = (valueRaw || defaultValue) as NonNullable<D2>;

  const setValue = (newValue: NewValueType<D>, updateType?: UrlUpdateType): void => {
    let n: D;

    if (newValue instanceof Function) {
      // TODO type fix (D2 -> D conversion)
      n = newValue(value as unknown as D);
    } else {
      n = newValue;
    }

    // TODO type fix (if undefined)
    const newQueryParamValue = (isEqual(n, defaultValue) ? undefined : n) as D;

    setValueRaw(newQueryParamValue, updateType);
  };

  return [value, setValue];
};

Usage:

const [pageNumber, setPageNumber] = useQueryParamDefault('page', NumberParam, 1);

if I call setPageNumber(1) the query param disappear as I expected.

Duplicates #138