DEV Community

Sushil
Sushil

Posted on

How to Revalidate the generateStaticParams in Nextjs

Currently, I am building my blog app. I am using the generateStaticParams. The problem is that it is not revalidating the API as I added a new blog which is not generated with the static params when I console log it.

The code

export const revalidate = 60
export async function generateStaticParams() {

    const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/posts`,
        {
            next: { revalidate: 10 }
        }
    );

    const { posts }: PostsResponse = await res.json()
    console.log("first:::", posts)
    return posts.map(({ slug }) => {
        return {
            slug
        }
    })
}

export async function generateMetadata({
    params,
}: {
    params: Params;
}): Promise<Metadata> {
    try {
        const { slug } = params;
        const response = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/posts/${slug}`);
        const blog: Post = await response.json();

        return {
            title: blog.title,
            description: blog.excerpt,
            openGraph: {
                images: [
                    {
                        url: blog.img
                    }
                ]
            }
        };
    } catch (error) {
        console.error("Error fetching metadata:", error);
        throw new Error("Error fetching metadata");
    }
}

const getData = async (slug: string) => {

    const res = await fetch(`${process.env.NEXT_PUBLIC_BASE_URL}/api/posts/${slug}`,
        {
            next: { revalidate: 10 }
        });

    if (res.status === 404) {
        throw new Error("something went wrong")
    }
    return res.json();
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)