Reputation: 849
When using Next.js dynamic routing I'm trying to make an SWR fetch request using the routing query object, but my SWR fetch request is being called before the query object is set.
Given the dynamic route /posts/[id]
, consider the page /posts/123
.
import { useRouter } from 'next/router';
import useSWR from 'swr';
export default function MyPage() {
const router = useRouter();
const { id } = router.query;
const url = `https://my.api.com/posts/${id}` // I've also tried using let here
const { data, error } = useSWR(url, fetcher);
console.log(url)
This URL initially console logs as https://my.api.com/posts/undefined
and an error is returned from the API because https://my.api.com/posts/undefined
is, of course, not a valid path.
Immediately after, the URL console logs correctly as https://my.api.com/posts/123
and the data on the page usually then populates, but sometimes the data doesn't populate and it's stuck in a 'loading' state. When I hardcode the URL this never happens.
Is there something I'm doing wrong here? Why is the query object not available immediately? Is there a way to elegantly wait for it to be set?
Upvotes: 14
Views: 5973
Reputation: 867
You could try to use conditional data fetching like so:
const { data, error } = useSWR(id ? url : null, id ? fetcher : null);
Also check following conversation: https://github.com/vercel/next.js/discussions/15952
Upvotes: 19