在 Next.js 中使用 revalidateTag 获取数据不起作用 – 我漏掉了什么?

huangapple go评论59阅读模式
英文:

Fetching data in Next.js with revalidateTag doesn't work - what am I missing?

问题

I'm using next 13.4.3 and I'm trying to revalidate my fetch data with next fetch wrapper through revalidateTag. I can't find the proper way to make this work. In production mode (next build & next start) nothing gets re-rendered. Is this feature not working at all? I spent the last day trying to make this work with graphql-request and since it doesn't work with basic fetch here I am.

我正在使用 next 13.4.3,尝试使用 next fetch wrapper 通过 revalidateTag 重新验证我的数据获取。我找不到使其正常工作的正确方法。在生产模式下(next build 和 next start),没有任何内容被重新渲染。这个功能是否完全不起作用?我花了最后一天尝试使其与 graphql-request 配合工作,但由于基本 fetch 不起作用,我只好在这里尝试。

I followed the docs: https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating#on-demand-revalidation

我遵循了文档:https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating#on-demand-revalidation

I made an api endpoint where it calls the revalidateTag method, and I made a special page to test this out.
Here is the code for the api:

我创建了一个 API 端点,其中调用了 revalidateTag 方法,我还创建了一个特殊页面来测试它。以下是 API 的代码:

import { revalidateTag } from 'next/cache';
import { NextRequest, NextResponse } from 'next/server';

export const POST = async (req: NextRequest) => {
  revalidateTag('a');
  console.log('revalidated');
  return NextResponse.json({ revalidated: true, now: Date.now() });
};

Here is the code of the page:

以下是页面的代码:

const page = async () => {
  const res = await fetch('http://127.0.0.1:1337/graphql', {
    method: 'POST',
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      query: `
        query Settings($locale: I18NLocaleCode!) {
          setting(locale: $locale) {
            data {
              attributes {
                seo {
                  title
                }
              }
            }
          }
        }
      `,
      variables: {
        'locale': 'fr',
      },
    }),
    next: { tags: ['a'] }
  });
  const { data } = await res.json();
  return (
    <div>{data && data.setting.data.attributes.seo.title}</div>
  )
}

export default page;

您可以使用以上代码进行翻译。

英文:

i'm using next 13.4.3 and i'm trying to revalidate my fetch data with next fetch wrapper through revalidateTag. I can't find the proper way to make this work. In production mode (next build & next start) nothing get's re-rendered. Is this feature not working at all ? I spent the last day trying to make this work with graphql-request and since it doesn't work with basic fetch here i am.

I followed the docs : https://nextjs.org/docs/app/building-your-application/data-fetching/revalidating#on-demand-revalidation

I made an api endpoint where it call the revalidateTag method, and i made a special page to test this out.
Here is the code for the api :

import { revalidateTag } from &#39;next/cache&#39;;
import { NextRequest, NextResponse } from &#39;next/server&#39;;

export const POST = async (req: NextRequest) =&gt; {
  revalidateTag(&#39;a&#39;);
  console.log(&#39;revalidated&#39;);
  return NextResponse.json({ revalidated: true, now: Date.now() });
};

Here is the code of the page :

const page = async () =&gt; {
  const res = await fetch(&#39;http://127.0.0.1:1337/graphql&#39;, {
    method: &#39;POST&#39;,
    headers: {
      &quot;Content-Type&quot;: &quot;application/json&quot;
    },
    body: JSON.stringify({
      query: `
        query Settings($locale: I18NLocaleCode!) {
          setting(locale: $locale) {
            data {
              attributes {
                seo {
                  title
                }
              }
            }
          }
        }
      `,
      variables: {
        &#39;locale&#39;: &#39;fr&#39;,
      },
    }),
    next: { tags: [&#39;a&#39;] }
  });
  const { data } = await res.json();
  return (
    &lt;div&gt;{data &amp;&amp; data.setting.data.attributes.seo.title}&lt;/div&gt;
  )
}

export default page;

答案1

得分: 0

The above code works, and since I made this work on GraphQL (with graphql-request), here is the code of the query function that I call in my page.tsx:

export const Client = new GraphQLClient(`${API_URL}/graphql` as string, {
  headers: {
    authorization: TOKEN ? `Bearer ${TOKEN}` : '',
  },
  fetch: fetch,
});

export const QuerySettings = async (locale: string) => {
  const queryVariables = {
    locale: locale,
  };

  // Add revalidate tags to Next.js fetch
  Client.requestConfig.fetch = (url, options) => fetch(url, { ...options, next: { tags: ['settings'] } });

  const { setting } = await Client.request<{
    setting: {
      data: Setting;
    };
  }>(
    gql`
      query Settings($locale: I18NLocaleCode!) {
        setting(locale: $locale) {
          data {
            attributes {
              seo {
                title
              }
            }
          }
        }
      }
    `,
    queryVariables
  );

  return setting.data.attributes;
};
英文:

Ok that's my bad on this one, I didn't check if it was re re-rendering after a second refresh. As a comment said the feature works correctly, next start re-rendering the page on the first request that you get after revalidation so a second request will get new datas.

The above code works, and since I made this works on graphql (with graphql-request) here is the code of the query function that i call in my page.tsx :

export const Client = new GraphQLClient(`${API_URL}/graphql` as string, {
  headers: {
    authorization: TOKEN ? `Bearer ${TOKEN}` : &#39;&#39;,
  },
  fetch: fetch,
});

export const QuerySettings = async (locale: string) =&gt; {
  const queryVariables = {
    locale: locale,
  };

  //Add revalidate Tags to next.js fetch
  Client.requestConfig.fetch = (url, options) =&gt; fetch(url, { ...options, next: { tags: [&#39;settings&#39;] } });

  const { setting } = await Client.request&lt;{
    setting: {
      data: Setting;
    };
  }&gt;(
    gql`
      query Settings($locale: I18NLocaleCode!) {
        setting(locale: $locale) {
          data {
            attributes {
              seo {
                title
              }
            }
          }
        }
      }
    `,
    queryVariables
  );

  return setting.data.attributes;
};

huangapple
  • 本文由 发表于 2023年5月22日 05:09:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76301930.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定