Closed d9k closed 2 years ago
I want to unset url param if new value is default. Couldn't achieve this behavior using withDefault().
withDefault()
Eventually I wrote my own hook which wraps useQueryParam() but I need help with typescript typings:
useQueryParam()
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.
setPageNumber(1)
Duplicates #138
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:Usage:
if I call
setPageNumber(1)
the query param disappear as I expected.