skip to Main Content

I tried to implement the SSG operation with {cache: ‘force-cache’} fetch option, but I always returned the same data even if the mock server’s data changed.

{ The cache: ‘no-store’} fetch option changes the data, but this is an SSR method, so I didn’t think it was suitable for my site to create a blog.

I’m trying to use axios to find another way, but I don’t think I’ve ever used axios in the Next.js 13 version.
How can I implement the SSG behavior with axios in version 13 of Next.js?

import Layout_Mobile from "@/components/Layout/DeviceLayout/Layout_Mobile";
import Layout_PC from "@/components/Layout/DeviceLayout/Layout_PC";
import PostDetailPage from "@/components/PostDetailPage/PostDetailPage";

const fetchPosts = async (params) => {
  const res = await fetch(
    `https://5875183d-18c0-49ad-b99d-8deeb4ded6a9.mock.pstmn.io/posts/${params.slug}`,
    {
      cache: "force-cache",
    }
  )
    .then((response) => response.json())
    .then((data) => {
      return data;
    });

  return res;
};

export const generateStaticParams = async () => {
  const res = await fetch(
    "https://5875183d-18c0-49ad-b99d-8deeb4ded6a9.mock.pstmn.io/posts"
  )
    .then((response) => response.json())
    .then((data) => {
      return data;
    });

  return res.map((post) => ({
    slug: post.id.toString(),
  }));
};

const page = async ({ params }) => {
  const { title, summary, content, author, createdAt } = await fetchPosts(
    params
  );

  return (
    <div>
      <Layout_Mobile></Layout_Mobile>
      <Layout_PC>
        <PostDetailPage
          title={title}
          description={summary}
          content={content}
          author={author}
          date={createdAt}
        />
      </Layout_PC>
    </div>
  );
};

export default page;

I really want to solve this problem…

3

Answers


  1. In Next.js version 13, you can use the axios library to fetch data and implement Static Site Generation (SSG). To achieve SSG behavior with axios, you can use the getStaticPaths and getStaticProps functions in your page. Here’s an example of how you can modify your code:

    import Layout_Mobile from "@/components/Layout/DeviceLayout/Layout_Mobile";
    import Layout_PC from "@/components/Layout/DeviceLayout/Layout_PC";
    import PostDetailPage from "@/components/PostDetailPage/PostDetailPage";
    import axios from 'axios';
    
    const fetchPosts = async (slug) => {
      const response = await axios.get(`https://5875183d-18c0-49ad-b99d-8deeb4ded6a9.mock.pstmn.io/posts/${slug}`);
      return response.data;
    };
    
    export const getStaticPaths = async () => {
      const response = await axios.get("https://5875183d-18c0-49ad-b99d-8deeb4ded6a9.mock.pstmn.io/posts");
      const posts = response.data;
    
      const paths = posts.map((post) => ({
        params: { slug: post.id.toString() },
      }));
    
      return { paths, fallback: false };
    };
    
    export const getStaticProps = async ({ params }) => {
      const { title, summary, content, author, createdAt } = await fetchPosts(params.slug);
    
      return {
        props: {
          title,
          summary,
          content,
          author,
          date: createdAt,
        },
      };
    };
    
    const PostPage = ({ title, summary, content, author, date }) => {
      return (
        <div>
          <Layout_Mobile></Layout_Mobile>
          <Layout_PC>
            <PostDetailPage
              title={title}
              description={summary}
              content={content}
              author={author}
              date={date}
            />
          </Layout_PC>
        </div>
      );
    };
    
    export default PostPage;
    

    In this example:

    I replaced the fetch function with axios.get for data fetching.

    I introduced getStaticPaths to specify the dynamic paths for which static pages should be generated.

    I used getStaticProps to fetch the specific post data for a given path.

    Login or Signup to reply.
  2. The native fetch Web API has also been extended in React and Next.js. It automatically dedupes fetch requests and provides one flexible way to fetch, cache, and revalidate data at the component level. This means all the benefits of Static Site Generation (SSG), Server-Side Rendering (SSR), and Incremental Static Regeneration (ISR) are now available through one API:

    // This request should be cached until manually invalidated.
    // Similar to `getStaticProps`.
    // `force-cache` is the default and can be omitted.
    fetch(URL, { cache: 'force-cache' });
     
    // This request should be refetched on every request.
    // Similar to `getServerSideProps`.
    fetch(URL, { cache: 'no-store' });
     
    // This request should be cached with a lifetime of 10 seconds.
    // Similar to `getStaticProps` with the `revalidate` option.
    fetch(URL, { next: { revalidate: 10 } });
    

    This information is taken from: https://nextjs.org/blog/next-13

    You can use the revalidate option: Revalidation is the process of purging the Data Cache and re-fetching the latest data. This is useful when your data changes and you want to ensure you show the latest information.
    In Next version 13 only with the using of fetch you can make similar behavior for the getStaticProps, I hope this can be useful for you.

    Login or Signup to reply.
  3. It’s totally fine to use Axios with Next.js 13, but I recommend using SWR [React Hooks for Data Fetching]. It is based on the concept called stale-while-revalidate. With SWR, components will get a stream of data updates constantly and automatically.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search