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
as the docs says you cannot generate metadata in a client component.
As per the code here, you have fetched the meta data in
metadata
. Now you might need to populate it in the return of thePage
method. Also consider callingGenerateMetaDataTags()
before the return and consider removing the callexport const metadata = GenerateMetaDataTags();
in the last line. When you say metadata, I am assuming it is the data in themeta
tags which goes in theHead
component like.You can read more about rendering for pages router, or for app router.