Last active
May 13, 2022 10:12
-
-
Save eesa1980/1f21275b85840d8215b9c69f989ceada to your computer and use it in GitHub Desktop.
A hook in react to return url params #React #CustomHook #URLSearchParams
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
/** | |
* A hook in react to return url params | |
*/ | |
export const useUrlParams = () => { | |
const location = useLocation() | |
const [search] = useState<URLSearchParams>( | |
new URLSearchParams(location.search) | |
) | |
return useCallback( | |
<T extends unknown>(...param: string[]): T => { | |
const obj: Record<string, unknown> = {} | |
param.forEach((p: string) => { | |
if (p !== null) { | |
obj[p] = search.get(p) | |
} | |
}) | |
return <T>obj | |
}, | |
[search] | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment