👀 Our most exciting product launch yet 🚀 Join us May 8th for Sanity Connect

Next.js GetStaticProps - How to Fetch Multiple Types on the Same Page

1 replies
Last updated: Jul 13, 2021
Hi guys, I am using the Sanity Client to fetch data with next js using the getStaticProps for pages like about, contact etc etc
Now fetching works but I also want to fetch a different type like “authors” on the same page and map through them.

But i don’t want to copy paste the client? How can I fetch multiple types on one page.

thanks!

Code:


import  sanityClient  from "../lib/client";
import { aboutQuery, teamQuery } from "../lib/queries";

const People = ({ context }) => {
    const { title, author } = context;

    console.log(context);

    return (
        <div>
            <h2>{title}</h2>
            <p>{author.name}</p>
        </div>
    )
}

export default People;

export async function getStaticProps() {
    const context = await sanityClient.fetch(aboutQuery, teamQuery);


    return { props: { context } };
  }
Queries:


export const aboutQuery = `*[_type == "page" && title == "About"][0]{
    _id,
    title,
    slug,
    author-> {
        name
    }
}`;

export const teamQuery = `*[_type == "author"]{
    _id,
    bio,
    slug,
    jobTitle,
    name,
    authorImage,
}`;

Jul 13, 2021, 10:43 AM
you can query for multiple types like this:
{
  'type1': *[_type == 'type1'], 
  'type2': *[_type == 'othertype'] }
So in your case you can probably import both queries &amp; reuse them:


client.fetch(`
  {
    'team': ${teamQuery},
    'about': ${aboutQuery},
  }
`)
Jul 13, 2021, 3:46 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?