For dynamic pages, you can add metadata
by not exporting a constant or variable named metadata,
but by instead exporting an async function called
generateMetadata.
And it must be called like this
because NextJS is also looking for functions like this.
If it doesn't find any other metadata,
it's checking whether there is such a function,
and if there is such a function, NextJS will execute it
for you and then it's your job
to return such a metadata object in that function.
Now how does that help us with dynamic data?
Well, this function receives the same data
our page component receives as props.
So here we also get an object with a params key,
and that of course allows us to get the meal
for which the metadata should be generated
by simply accessing mealSlug and passing that to getMeal.
Well, and with that, we can then return a title
that's set equal to meal title
and a description that's set to meal.summary,
for example, and that's
how we can generate the metadata for a dynamic page.
With that, if we now visit a meal, we can see its title,
its name represented here in the tab title.
Now if we enter some invalid slug here,
we now get an error though instead of the not found page
because the metadata is actually generated first
and this now simply fails.
When I try to access title on meal,
that fails because meal is undefined.
So therefore we should actually add this if check here,
where we check whether the meal is maybe not defined,
and called the notFound function if it isn't,
inside of generate metadata to ensure
that we show the notFound page if generating
the metadata fails, which it does
if we don't find that meal.
With that, you see that now we get
that meal not found page again,
but that's how we can handle that metadata.