Next.js Discord

Discord Forum

How to correctly fetch data and use in the MetaData and on the page?

Answered
Great Dane posted this in #help-forum
Open in Discord
Great DaneOP
Hello! In this component, I fetch data for the page and the same data - to create dynamic metadata. How to fetch the data correctly without doing this twice.
import { imgProps } from "@/misc/stools";
import { IPost } from "@/misc/types";
import Post from "@/wrappers/Post";
import { Metadata, ResolvingMetadata } from "next";
import React from "react";

const HOST = process.env.NEXT_PUBLIC_HOST;

type Props = {
  params: { slug: string };
  searchParams: { [key: string]: string | string[] | undefined };
};

export async function generateMetadata(
  { params, searchParams }: Props,
  parent: ResolvingMetadata
): Promise<Metadata> {
  const slug = params.slug;

  const data: IPost[] = await fetch(`${HOST}/api/pub/news/${slug}`).then(
    (res) => res.json()
  );

  const content = data[0];

  return {
    title: content.title,
    description: content.text?.slice(0, 50) + "...",
    openGraph: {
      url: `${HOST}/news/${slug}`,
      title: content.title,
      description: content.text?.slice(0, 50) + "...",
      images:
        content.photos && content.dir
          ? [{ url: `${HOST}/dist/${content.dir}/${content.photos[0]}`, ...imgProps(content.title) }]
          : [{ url: `${HOST}/main.jpg`, ...imgProps(content.title) }],
    },
  };
}

async function getData(slug: string) {
  const res = await fetch(`${HOST}/api/pub/news/${slug}`);

  if (!res.ok) {
    throw new Error("Failed to fetch data");
  }

  return res.json();
}

export default async function Page({ params, searchParams }: Props) {
  const { slug } = params;
  const data = await getData(slug);

  return <Post data={data[0]} />;
}
Answered by DirtyCajunRice | AppDir
next natively groups them and only makes 1 call. so its already happening
View full answer

4 Replies

next natively groups them and only makes 1 call. so its already happening
Answer
@Great Dane Hello! In this component, I fetch data for the page and the same data - to create dynamic metadata. How to fetch the data correctly without doing this twice. import { imgProps } from "@/misc/stools"; import { IPost } from "@/misc/types"; import Post from "@/wrappers/Post"; import { Metadata, ResolvingMetadata } from "next"; import React from "react"; const HOST = process.env.NEXT_PUBLIC_HOST; type Props = { params: { slug: string }; searchParams: { [key: string]: string | string[] | undefined }; }; export async function generateMetadata( { params, searchParams }: Props, parent: ResolvingMetadata ): Promise<Metadata> { const slug = params.slug; const data: IPost[] = await fetch(`${HOST}/api/pub/news/${slug}`).then( (res) => res.json() ); const content = data[0]; return { title: content.title, description: content.text?.slice(0, 50) + "...", openGraph: { url: `${HOST}/news/${slug}`, title: content.title, description: content.text?.slice(0, 50) + "...", images: content.photos && content.dir ? [{ url: `${HOST}/dist/${content.dir}/${content.photos[0]}`, ...imgProps(content.title) }] : [{ url: `${HOST}/main.jpg`, ...imgProps(content.title) }], }, }; } async function getData(slug: string) { const res = await fetch(`${HOST}/api/pub/news/${slug}`); if (!res.ok) { throw new Error("Failed to fetch data"); } return res.json(); } export default async function Page({ params, searchParams }: Props) { const { slug } = params; const data = await getData(slug); return <Post data={data[0]} />; }
Pacific herring
Hi ! I need help about metadata. Im doing the exact same thing using generateMetadata. But for user page, Im fetching data from api, but how uptdate this data after ? like if the user change his name, the metdata title should change but it wasnt
@Pacific herring Hi ! I need help about metadata. Im doing the exact same thing using generateMetadata. But for user page, Im fetching data from api, but how uptdate this data after ? like if the user change his name, the metdata title should change but it wasnt
Can you create your own post as this post is solved (+old), and more people will be able to help... Also, can you try to include code snippets where possible, because that will assist us with helping...
@DirtyCajunRice | AppDir next natively groups them and only makes 1 call. so its already happening
Dunker
Thanks! Also is the generateMetadata called first under the hood or Page?