Use the data fetched from generateStaticParams (Next 14)

927 Views Asked by At

I am a bit surprise by how generateStaticParams seems to work.

We generally retrieve one id in order to generate each segment.

It's fine but, the API call used to do that, contains as well the necessary data to feed each pages that is going to be generated at build time.

But it does not seems possible to send as props the rest of the data fetched.

In my example, it means that at build time At build time next is going to call ArticleAPI.fetchByCategory for each pages with the parameter coming from generateStaticParams , while it could use the data coming from the fetch in generateStaticParams ?

So 1000 routes , means 1000 requests at build time instead of one that could provide the data for each page ?

In : /articles/categories/[category]/page.ts

import { ArticleAPI } from "@/api/article-api";
import { ArticleList } from "@/components/ArticleList/ArticleList";
import { Article, ArticleCategory } from "@/types/article-type";

export async function generateStaticParams() {
  const articlesByCat = await ArticleAPI.fetchAllCategories();
  const params = Object.keys(articlesByCat).map((category) => {
    const articles = articlesByCat[category];
    return {
      params: {
        category,
        articles, // I though I could send this to the component ?
      },
    };
  });

  return params;
}
export default async function ArticlesFilteredByCategories(p: {
  params: { category: ArticleCategory; articles: Article[] };
}) {

  // But here p.params only contains the category and not the articles...
  // { category : "business" } for example when navigating on 
  //  /articles/categories/business

  // I wish I could receive the articles as props from generateStaticParams
  // Instead I have to specify a fetch here ( If I have 100 pages, 
  //I will have 100 api call at build time) while the data was already there in generateStaticParams()

  const articles = await ArticleAPI.fetchByCategory(p.params.category);
  return (
    <ArticleList
      articles={articles}
    />
  );
}
1

There are 1 best solutions below

2
On

when you build your app, next.js does an analysis to determine dynamic and static routes. By default [dynamicParam] route is considered to be a dynamic route. that means no caching strategy is applied. So, every time this route is visited, next.js will dynamically build this page and this takes time.

generateStaticParams helps you prebuilt page for each item in the database and this HTML will be cached. your app will be serving

generateStaticParams is similar to getStaticPaths in previous next.js versions. But before we could prebuilt only the most popular items and cache them if we had a large dataset. If a user visits a dynamic page that is not cached we could build it dynamically (if you remember fallback option). I do not think that generateStaticParams has such an option as of now.