Last active
October 18, 2022 05:14
-
-
Save kriskarpenko/c967413b6775854ac422dae7dafaefa4 to your computer and use it in GitHub Desktop.
useQueryParams hook for React Router v6
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 { useSearchParams } from "react-router-dom"; | |
/** | |
* Hook to get all query params as key value pairs. | |
* Usage: | |
* const {param1, param2} = useQueryParams() | |
* const queryParams = useQueryParams() | |
* @returns {} object with all query params as key value pairs | |
*/ | |
export function useQueryParams() { | |
const [searchParams] = useSearchParams(); | |
const result = {}; | |
searchParams.forEach((value, key) => (result[key] = value)); | |
return result; | |
} |
This code is more clear
searchParams.forEach((value, key) => {
result[key] = value
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, can you provide example of usage?