Next.js Discord

Discord Forum

How to deal with generateMetadata using suspense and a promise as component props?

Answered
Masai Lion posted this in #help-forum
Open in Discord
Masai LionOP
If I have this page, how do I best deal with the await here?

Should I await id and fetchproduct in the page and send the resolved product or should I do like I do now? If I do that I can't use suspense this way right?

But if I do what I do now, should I still await the product in the generateMetadata since it needs to be resolved there? If so, how does the cache work, does it still cache the fetch?

export async function generateMetadata({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const data = await fetchProduct(id);
  return {
    title: data.title,
  };
}

//get the dynamic id from the page url and use that to fetch products
export default async function ProductPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  //since params is a promise we have to await it first
  const { id } = await params;
  //fetch product but don't wait for it here, waitin is in the Card instead
  const data = fetchProduct(id);
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <ProductDetailsCard product={data} />
    </Suspense>
  );
}
Answered by B33fb0n3
if you just want to have the loading suspense boundary around your page, then you can await the fetchProduct inside your page and add a loading.tsx to show a loading screen.

The generateMetadata looks good for me and can stay like that. I assume you using React.cache inside your fetchProduct function to dedupe the calls to your DB
View full answer

5 Replies

Answer
Masai LionOP
Thank you! I am using fetch here at the moment and so I was thinking about this, thus my question about the cache: "fetch requests are automatically memoized for the same data across generateMetadata, generateStaticParams, Layouts, Pages, and Server Components. React cache can be used if fetch is unavailable." - https://nextjs.org/docs/app/api-reference/functions/generate-metadata. Is that still in effect or do I need to use react cache doing it this way?
Masai LionOP
Cool, thank you for the fast reply!
sure thing