Created
August 31, 2021 01:52
-
-
Save max10rogerio/585ea597271c844a29657d00fc4d9bd8 to your computer and use it in GitHub Desktop.
useQuery Hook - React with react-router-dom - TS
This file contains hidden or 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 { useLocation } from "react-router-dom"; | |
/** | |
* Get URL query params as object | |
* | |
* Example: | |
* | |
* ```tsx | |
* type Query = { | |
* q: string | |
* } | |
* | |
* const MyComponent = () => { | |
* const { q } = useQuery<Query>(); | |
* | |
* return ( | |
* <h1>{q}</h1> | |
* ); | |
* } | |
* ``` | |
*/ | |
export const useQuery = <T = Record<string, any>>(): Partial<T> => { | |
const location = useLocation(); | |
const urlSearchParams = new URLSearchParams(location.search); | |
const queryParams = Object.fromEntries(urlSearchParams); | |
return queryParams as any; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment