最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Use Next.js Dynamic routing query object in an SWR fetch request - Stack Overflow

programmeradmin8浏览0评论

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 = `/${id}`    // I've also tried using let here
  const { data, error } = useSWR(url, fetcher);
  
  console.log(url)

This URL initially console logs as and an error is returned from the API because is, of course, not a valid path.

Immediately after, the URL console logs correctly as 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?

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./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./posts/undefined and an error is returned from the API because https://my.api./posts/undefined is, of course, not a valid path.

Immediately after, the URL console logs correctly as https://my.api./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?

Share Improve this question asked Feb 24, 2021 at 8:52 GrantGrant 8491 gold badge9 silver badges19 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 19

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./vercel/next.js/discussions/15952

发布评论

评论列表(0)

  1. 暂无评论