I’m facing an issue while trying to access query parameters in Next.js 13 using the useRouter hook. When I run the following code
'use client'
import { useRouter } from 'next/navigation';
const Post = () => {
const router = useRouter();
return (
<div>
post number : {router.query.id}
</div>
)
}
export default Post
I receive the following error:
Unhandled Runtime Error
TypeError: router.query is undefined
Source
25 | return (
26 | <div>
> 27 | post number : {router.query.id}
| ^
28 | </div>
29 |
30 | )
i take the code from the official website Routing:Dynamic Routes,
you can look here
i log it in the console to see what inside the variable router, i get this this
2
Answers
i got the answer that it worked for me (getting URL params)
I encountered the issue while trying to access query parameters using the
useRouter
hook fromnext/router
inside the app directory in Next.js. After referring to the Next.js documentationTo resolve this issue, you can make use of the
useParams
hook from thenext/navigation
package. This hook provides a solution for getting URL params , without relying on useRouter.Here's an example of the modified code that successfully access query parameters:
By using
useParams
, you can directly destructure theid
parameter from the route and utilize it within your component.Keep in mind that the example code assumes you are using the latest version of Next.js (v13.4.6).
The error you are getting is because the router.query object is not ready yet when the component first renders. This is because Next.js pre-renders pages on the server, and the query parameters are not available at that time.
To fix this, you can use the useEffect hook to wait until the router is ready before accessing the query parameters.
See the below code:
After fixing that, your code should work.I am giving the docs reference here: