Dynamic Metadata - prevent two database calls?
Unanswered
English Spot posted this in #help-forum
English SpotOP
I am trying to use dynamic head titles for each page that is server rendered based on a post
id. It seems redundant to have to fetch from the database twice, one for the metadate title and one for the page content. is there a way to only make one call to the database? Code snippet here: //...
export async function generateMetadata({ params }) {
const { id } = params;
const docRef = doc(db, "bananaResponses", id);
const docSnapshot = await getDoc(docRef);
if (docSnapshot.exists()) {
var title = docSnapshot.data().word;
return {
title: `${title} | Explain But Use Bananas`,
};
} else {
return {
title: `Not Found | Explain But Use Bananas`,
};
}
}
export default async function Page({ params }) {
const { id } = params;
const docRef = doc(db, "bananaResponses", id);
const docSnapshot = await getDoc(docRef);
if (docSnapshot.exists()) {
var data = docSnapshot.data();
} else {
// TODO: make 404 page
return <div>Not Found</div>;
}
return (
<main className="main">
<div className="container">
//...1 Reply
@English Spot I am trying to use dynamic head titles for each page that is server rendered based on a post `id`. It seems redundant to have to fetch from the database twice, one for the metadate title and one for the page content. is there a way to only make one call to the database? Code snippet here:
js
//...
export async function generateMetadata({ params }) {
const { id } = params;
const docRef = doc(db, "bananaResponses", id);
const docSnapshot = await getDoc(docRef);
if (docSnapshot.exists()) {
var title = docSnapshot.data().word;
return {
title: `${title} | Explain But Use Bananas`,
};
} else {
return {
title: `Not Found | Explain But Use Bananas`,
};
}
}
export default async function Page({ params }) {
const { id } = params;
const docRef = doc(db, "bananaResponses", id);
const docSnapshot = await getDoc(docRef);
if (docSnapshot.exists()) {
var data = docSnapshot.data();
} else {
// TODO: make 404 page
return <div>Not Found</div>;
}
return (
<main className="main">
<div className="container">
//...
use cache() which handles deduplication for you
https://nextjs.org/docs/app/building-your-application/data-fetching/caching#react-cache
https://nextjs.org/docs/app/building-your-application/data-fetching/caching#react-cache