56
loading...
This website collects cookies to deliver better user experience
useQueryParam
which let you manage 1 query parameter in the same way as useState
worked.useQueryParam
is that it respects all other queries that you currently store in the url.function SearchInput() {
const [searchTerm, setSearchTerm] = useQueryParam('q', StringParam);
return <input onChange={(event) => setSearchTerm(event.target.value)} value={searchTerm} />
}
useSearchParams
which is great and it was really missing something like that from v5.use-query-param
library.serialize-query-param
library which is authored by the same person who wrote use-query-params
. The hook I wrote works in the same way as useState
.function SearchInput() {
const [searchTerm, setSearchTerm] = useSearchParam('q', StringParam);
const changeSearchTerm = (event: React.ChangeEvent<HTMLInputElement>): void => {
setSearchTerm(event.target.value, 'replace');
// you could also use a callback function to set the value like this
setSearchTerm((oldValue) => {
// do something with oldValue if you like
return event.target.value;
}, 'replace') // replace or push to url (push is default)
}
return <input onChange={} value={searchTerm} />
}
UNSAFE_NavigationContext
from react router. As far as I can tell it's okayish to use it. There are some issues on the react-router repo discussing this but as of writing this theyimport { isString } from 'lodash';
import { useContext } from 'react';
import { UNSAFE_NavigationContext, useSearchParams } from 'react-router-dom';
import { QueryParamConfig, StringParam } from 'serialize-query-params';
type NewValueType<D> = D | ((latestValue: D) => D);
type UrlUpdateType = 'replace' | 'push' | undefined;
type UseSearchParam<D, D2 = D> = [D2, (newValue: NewValueType<D>, updateType?: UrlUpdateType) => void];
export default function useSearchParam<D, D2 = D>(
name: string,
config: QueryParamConfig<D, D2> = StringParam as QueryParamConfig<any>,
): UseSearchParam<D, D2> {
const [searchParams, setSearchParams] = useSearchParams();
const { navigator } = useContext(UNSAFE_NavigationContext);
const setNewValue = (valueOrFn: NewValueType<D>, updateType?: UrlUpdateType): void => {
let newValue;
const value = searchParams.get(name);
if (typeof valueOrFn === 'function') {
// eslint-disable-next-line @typescript-eslint/ban-types
newValue = (valueOrFn as Function)(config.decode(value));
} else {
newValue = valueOrFn;
}
const encodedValue = config.encode(newValue);
const params = new URLSearchParams((navigator as any).location.search);
if (isString(encodedValue)) {
params.set(name, encodedValue);
} else {
params.delete(name);
}
setSearchParams(params, { replace: updateType === 'replace' });
};
const decodedValue = config.decode(searchParams.get(name));
return [decodedValue, setNewValue];
}