Last active
April 26, 2022 13:35
-
-
Save ValentaTomas/70eed9ed6c63624d18040924dea4f6ed to your computer and use it in GitHub Desktop.
Hook for extracting route query parameters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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