skip to Main Content

So the problem is I have a product page in which I’m getting metadata for that particular product page from backend i.e. from database using an API. I have to use a custom hook to fetch data from that API, Now the Problem is I can’t use that metadata from the "use client" directive.

I can’t share my whole code As it’s 500+ lines so here’s a glimpse what I am trying to do!

"use client"
import React from "react";
import useGetData from "./useGetData";

const Page = () => {
   const { data } = useGetData();
   return (
      <div>
      Some use of {data}
      </div>
   );
}

export default Page;

const GenerateMetaDataTags = () => {
  const { propId } = useParams();
  const { data, loading, error } = useGetData(propId);
  const metaData = {};

  data.forEach((ele) => {
    metaData[ele.name] = ele.content;
  });

  if (!loading) {
    return metaData;
  }
};

export const metadata = GenerateMetaDataTags();

I want this Data to update on the client side after fetching from the database.

I tried a lot of different approaches like using layout.js and all but I have to use hook to get the data from database and the hook will always need the "use client";

2

Answers


  1. as the docs says you cannot generate metadata in a client component.

    Login or Signup to reply.
  2. As per the code here, you have fetched the meta data in metadata. Now you might need to populate it in the return of the Page method. Also consider calling GenerateMetaDataTags() before the return and consider removing the call export const metadata = GenerateMetaDataTags(); in the last line. When you say metadata, I am assuming it is the data in the meta tags which goes in the Head component like.

    import Head from 'next/head'
    
    ...
    ...
    const Page = () => {
       const { data } = useGetData();
    
       const metadata = GenerateMetaDataTags();
    
      return (
    <>
        <Head>
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />
          <meta name="msapplication-TileColor" content="#000000" />
          <meta name="msapplication-config" content="/favicon/browserconfig.xml" />
          <meta name="ele1" content={metaData["ele1"]} />
          <meta name="ele2" content={metaData["ele2"]} />
        </Head>
    
        <SomeComponent>
         <div>
          Some use of {data}
         </div>
        </SomeComponent>
    
    </>);
    }
    ...
    ...
    
    

    You can read more about rendering for pages router, or for app router.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search