Next.js Discord

Discord Forum

Dynamic Metadata - prevent two database calls?

Unanswered
English Spot posted this in #help-forum
Open in Discord
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