Next.js Discord

Discord Forum

Generate dynamic pages with a given slug and retrieve the data using a parameter other than the slug

Unanswered
Indian oil sardine posted this in #help-forum
Open in Discord
Indian oil sardineOP
Context: I would like to generate dynamic pages with a slug from a CMS and retrieve the associated data for that slug using the page's ID.

I have no issues generating the pages dynamically with the correct slug using the following code.

my app/[slug]/page.tsx :

export async function generateStaticParams() {
  const { data }: { data: GetAllPagesQuery } = await getClient().query({
    query: GetAllPagesDocument,
  });
  return data.allPage.map((page) => {
    return {
      slug: page.slug?.current,
    };
  });
}

export default function Page({ params }: { params: { slug?: string | null } }) {
  return <div>{`slug: ${params.slug}`}</div>;
}


Now I would like to retrieve the data associated with the generated page, and for that, I have access to a query exposed by the CMS Sanity.

query GetPage($id: ID!) {
  Page(id: $id) {
    _key
    slug {
      current
    }
    sections {
      ...projectsSectionFragment
      ...contactSectionFragment
      ...aboutSectionFragment
    }
  }
}


My problem is as follows: generateStaticParams does not allow passing any parameters other than those used for generating the slugs, so I don't have the option to pass the ID through this method. Therefore, I would like to know if there is a way to generate dynamic pages with a given slug and retrieve the associated data using a query that uses an argument other than the slug, such as an ID ?

I know I can use getAllPagesQuery and filter on slug.current, but I find that approach very weird.

0 Replies