Problem: query
Object Always Empty
TL;DR: During first render, query
is empty and Router.isReady
is false
. In all following render calls, everything is back to normal.
In recent versions, dynamic routing is fully supported. The docs even show a super simple example of how it works. Sadly, for some reason, the docs fail to mention the important issue of hydration. This blog post explains some extra details.
The gist is: in many dynamic rendering scenarios (including the default), during initial render on the client, the page first gets rendered without any parameters (probably due to hydration, based on a static state that cannot take the dynamic path into account).
Solution
Allow your component to "kinda work" even if router.query
is empty, e.g.:
function MyComp() {
const router = useRouter();
const { id } = router.query;
console.log(`[MyComp render] router.isReady=${router.isReady}, id=${id}`);
useEffect(() => {
if (!router.isReady) {
return; // NOTE: router.query might be empty during initial render
}
doSomethingWithData(id);
}, [id, router.isReady]);
if (!router.isReady) {
// we are still waiting for dynamic data to be available
return 'loading...';
}
return theActualContent;
}
There even is the crucial Router.isReady
field that tells you whether query data is available, but, for some reason, they do not mention it in the Dynamic Routes
documentation.