Reputation: 11
I’m using Next.js 15 and encountering an issue where the API is being called twice, once from the generateMetadata()
function and once from the page component function. I also used React’s cache()
and wrapped the function that fetches the API with cache()
, but I’m still facing the same issue.
const fetchBlogsDetails = cache(async (blog_id: string, sessionID?: any) => {
const cookieString = sessionID
?.map((cookie: any) => `${cookie.name}=${cookie.value}`)
.join("; ");
console.log("🚀 ~ getBlogsDetails ~ blog_id1:", blog_id);
let blogDetails = [];
let blogTagsData = [];
const response = await fetch(
`${API_URL}blogDetails`,
{
method: "GET",
headers: { P_BLOG_ID: blog_id, Cookie: cookieString }
}
);
if (!response.ok) {
throw new Error("Error while fetching blogs Data");
}
try {
const res = await response.json();
if (!res?.items || res.items.length === 0) {
return null; // Blog not found
}
blogDetails = res?.items?.length > 0 ? res?.items[0] : null;
blogTagsData =
res?.items?.length > 0 ? res?.items[0]?.metatags?.split(",") : [];
return { blogDetails, blogTagsData };
} catch (err) {
console.log(err);
return null;
}
});
export const generateMetadata = async (props: {
params: Promise<{ blogId: string }>;
}) => {
const params = await props.params;
const fullUrl = `${appUrl}/blog/${params.blogId}`;
const cookie = (await cookies()).getAll();
const blogDetails = await fetchBlogsDetails(params.blogId, cookie);
const blogDetails1 = await fetchBlogsDetails(params.blogId, cookie);
console.log("🚀 ~ blogDetails1:", blogDetails1?.blogDetails?.title);
return {
title: blogDetails?.blogDetails?.metatitle,
};
};
const BlogDetailPage = async (props: {
params: Promise<{ blogId: string }>;
}) => {
const params = await props.params;
const blog_id = params.blogId;
// const fullUrl = `${appUrl}/blog/${params.blogId}`;
// const cookie = (await cookies()).getAll();
const blogDetails = await fetchBlogsDetails(params.blogId);
if (!blogDetails) {
notFound();
}
const loader = (
<div className="min-vh-100 min-vw-100 d-flex justify-content-center align-items-center">
<Loader />
</div>
);
return (
<>
<Suspense fallback={loader}>
<BlogDetails
blogDetailsData={blogDetails?.blogDetails}
blogTags={blogDetails?.blogTagsData}
/>
</Suspense>
</>
);
};
export default BlogDetailPage;
Upvotes: 0
Views: 9