Dynamic Metadata returns undefined
Answered
Rohu posted this in #help-forum
RohuOP
In a server component (page.tsx having as a parent [slug]) I am trying to get the dynamic metadata for each page. I am storing them in HyGraph which as you can see uses graphql (maybe is this the problem?)
In the console.log I am getting undefined, and in the app no title tag is being rendered.
query Works($slug: String!) {
works(where: {slug: $slug}) {
title
}
}
What could be the problem?
In the console.log I am getting undefined, and in the app no title tag is being rendered.
type Props = {
params: { slug: string };
};
export async function generateMetadata({ params }: Props): Promise<Metadata> {
// @ts-ignore
const product = await fetch(process.env.HYGRAPH_ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
query:query Works($slug: String!) {
works(where: {slug: $slug}) {
title
}
}
,
variables: {
slug: params,
},
}),
}).then((res) => res.json());
console.log(product.title);
return {
title: product.title,
};
}What could be the problem?
Answered by joulev
well the fetch gives something that doesn't have a
title. you need to debug the fetch4 Replies
see what the
product object actually is and find the title inside iti suspect you should do
product.data.title instead, but this is just a wild guess and nothing guarantees it can work. just console.log(product) to see what it isRohuOP
Hey, thanks for the answer!
You were right, there was something wrong in the fetch.
If needed for someone else, this is the correct way:
query Works() {
works(where: {slug: "${params.slug}"}) {
title
}
}
You were right, there was something wrong in the fetch.
If needed for someone else, this is the correct way:
export async function generateMetadata({ params }: Props): Promise<Metadata> {
// @ts-ignore
const product = await fetch(process.env.HYGRAPH_ENDPOINT, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({
query:query Works() {
works(where: {slug: "${params.slug}"}) {
title
}
}
,
variables: {
slug: params,
},
}),
}).then((res) => res.json());
return {
title: product.data.works[0].title,
};
}