beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
33 lines (32 loc) • 1.2 kB
JavaScript
import { useHistory } from 'react-router-dom';
import { useCallback, useRef } from 'react';
import useDidMount from './useDidMount';
import useURLSearchParams from './useURLSearchParams';
/**
* Very similar to `useQueryParams`, it eases the process of manipulate a query string that handles multiple values
*/
const useQueryParams = (key, options = {}) => {
const history = useHistory();
const params = useURLSearchParams();
const initialisedRef = useRef(false);
const onMount = useDidMount();
const setParam = useCallback((nextValue) => {
params.delete(key);
if (nextValue) {
nextValue.forEach((value) => params.append(key, value));
}
if (options.replaceState) {
history.replace({ search: params.toString() });
return;
}
history.push({ search: params.toString() });
}, [options.replaceState, history]);
onMount(() => {
if (!params.has(key)) {
setParam(options.initialValue);
initialisedRef.current = true;
}
});
return [initialisedRef.current ? params.getAll(key) : options.initialValue, setParam];
};
export default useQueryParams;