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
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:
In this example:
I replaced the
fetch
function withaxios.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.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.
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.