Skip to content

Instantly share code, notes, and snippets.

@ValentaTomas
Last active April 26, 2022 13:35
Show Gist options
  • Save ValentaTomas/70eed9ed6c63624d18040924dea4f6ed to your computer and use it in GitHub Desktop.
Save ValentaTomas/70eed9ed6c63624d18040924dea4f6ed to your computer and use it in GitHub Desktop.
Hook for extracting route query parameters
import { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
type Params<T extends string> = { [key in T]: string };
// Returns object that contains all path query parameters listed in the `names` argument.
// If any path query parameters from the `names` is missing in the path, the returned object is undefined.
function useQueryParams<T extends string>(...names: T[]) {
const location = useLocation();
const [paramEntries, setParamEntries] = useState<{ [key: string]: string }>();
useEffect(() => {
const search = (location && location.search) || window.location.search;
const params = new URLSearchParams(search);
const parsedParamEntries = [...params.entries()]
.reduce((prev, [key, value]) => ({ ...prev, [key]: value }), {});
setParamEntries(parsedParamEntries);
}, [location.search, location]);
return names.reduce<Params<T> | undefined>((result, current) => {
if (!result) {
return undefined;
}
const value = paramEntries[current];
if (value === undefined || value === null) {
return undefined;
}
return {
...result,
[current]: value,
} as Params<T>;
}, {} as Params<T>);
}
export default useQueryParams;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment