I have an issue with titles of dynamic pages. I’m trying to get the title from fetched data, so the title of each page should be the name of product from fetched data. But for some reason it doesn’t work.
"use server";
type Props = {
params: { id: number };
searchParams: { [key: string]: string | string[] | undefined };
};
export async function generateMetadata(
{ params, searchParams }: Props,
parent: ResolvingMetadata
): Promise<Metadata> {
type ProductType = {
title: string;
body: string;
};
const productId = params.id;
const product = (await fetch(`https://..../${productId}`).then((res) => res.json())) as ProductType;
return {
title: `title: ` + product.title,
description: product.body,
};
}
async function fetchData(productId: number) {
const res = await fetch(
"https://..../" + productId
);
const result = await res.json();
return result;
}
type Product = {
title: string;
body: string;
};
export default async function ProductId({
params,
}: {
params: { productId: number };
}) {
const product = (await fetchData(params.productId)) as Product;
console.log(product);
return (
<div>
<h1>Product Card {params.productId}</h1>
<ProductCard
title={product.title}
someText={product.body}
/>
</div>
);
}
In this case I receive ‘title: underfined’ in the title of the page.
I also tried try catch method, and it returns an error.
New contributor
Katerina B10 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.