Created
May 26, 2022 19:32
-
-
Save souporserious/caa17f9b2ab033d51e29544f75e5d858 to your computer and use it in GitHub Desktop.
NextJS router params for the server and client.
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 { useRouter } from 'next/router' | |
import * as queryString from 'query-string' | |
/** Converts NextJS router params into an object that is run on both the server and client. */ | |
export function useRouterParams<Params>() { | |
const router = useRouter() | |
const query = queryString.parse(router.asPath.split('?')[1]) | |
return Object.fromEntries( | |
Object.entries(query).map(([key, value]) => [key, parseValue(value)]) | |
) as unknown as Partial<Params> | |
} | |
function parseValue(value) { | |
if (value === 'true') { | |
return true | |
} else if (value === 'false') { | |
return false | |
} else if (isNaN(value)) { | |
return value | |
} else { | |
return Number(value) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment