Dynamic metadata from getData
Answered
Northeast Congo Lion posted this in #help-forum
Northeast Congo LionOP
I need to set SEO per page from the getData call. Can I call my data fetch before my page render function?
Answered by Giant panda
export async function generateMetadata() {
const data = await getData()
return { ... }
}
export default async function Home() {
const data = await getData()
return <>...</>
}21 Replies
Northeast Congo LionOP
async function getData() {
try {
const url = '...';
const data = await fetch(url);
return data.json();
} catch(e) {
throw new Error('Could not connect to CMS!');
}
}
const { content, settings } = await getData();
export const metadata = {
title: content.SEO.Title,
description: content.SEO.Description,
}
export default async function Home() {
return (
<></>
)
}is this acceptable
but
how would I use it here
if my data fetch has to be inside
function Home()how can i acess the content.SEO properties which are cms driven
Giant panda
You fetch the same data in generateMetadata and in your component
Giant panda
export async function generateMetadata() {
const data = await getData()
return { ... }
}
export default async function Home() {
const data = await getData()
return <>...</>
}Answer
Giant panda
React does request deduplication so that it gets only fired once
so it only fires once
that issss sick
i was worried requesting same data would be a pain
but in that case thanks good sir
@Giant panda tsx
export async function generateMetadata() {
const data = await getData()
return { ... }
}
export default async function Home() {
const data = await getData()
return <>...</>
}
Northeast Congo LionOP
do u think if i built my backend with graphql that would provide better performance or u think its neglible here
Giant panda
GraphQL has nothing to do with performance
@Giant panda GraphQL has nothing to do with performance
Northeast Congo LionOP
just mean in terms of serving reduced cotnent
Giant panda
GraphQL is very special protocol. You shouldn't pick it in the hopes of reducing payload sizes and rather pick it if it's really useful in your use-case which solely depends on the data and access patterns.
It's impossible to give a general suggestion for that.