How to combine multiple GROQ queries in a single Sanity client call?

3 replies
Last updated: Jun 18, 2021
I have a homepage page with my Nextjs project. How can i add multiple groq queries for instance 3 blog posts, news posts both type have a name blog and news. How can I combine these 2? without having to call the sanityClient twice for each query? Thanks 🤗
AI Update

Great question! You can absolutely combine multiple GROQ queries into a single request using what's called a "projection object" syntax. This is more efficient than making separate client.fetch() calls.

Here's how to structure your query to fetch both blog posts and news posts in one request:

const query = `{
  "blogPosts": *[_type == "blog"][0...3]{
    name,
    // add other fields you need
  },
  "newsPosts": *[_type == "news"][0...3]{
    name,
    // add other fields you need
  }
}`;

const data = await sanityClient.fetch(query);
// Now you have: data.blogPosts and data.newsPosts

Important notes:

  1. Use regular template literals (backticks), not the groq tagged template literal when combining queries this way. The groq tag can cause parsing errors with this syntax.

  2. Use [0...3] for slicing - this is the GROQ slice syntax where three dots (...) excludes the right-hand index, so [0...3] gives you items 0, 1, and 2 (three items total). Two dots (..) would be inclusive.

  3. Wrap property names in quotes - the keys like "blogPosts" and "newsPosts" need to be quoted strings in the query.

The result will be a single object with both datasets:

{
  blogPosts: [...], // your 3 blog posts
  newsPosts: [...]  // your 3 news posts
}

This approach works perfectly with usePreview() as well, since you're passing a single query string. Much more efficient than multiple fetches! 🤗

Show original thread
3 replies
user A
Thank you!😃
user A
How would I apply this to the sanityClieny fetch thanks
Let’s say your fetch normally looks like this (storing in
data
):

client.fetch(`
  *[_type == "blog"][0]
`);
And you serialize your data like this:


<BlockContent blocks={data.content} serializers={serializers} />
Instead, you might query with a fetch like this:


client.fetch(`
  {
    'blog': *[_type == "blog"][0],
    'news': *[_type == "news"][0]
  }
`);
And serialize like this:


<BlockContent blocks={data.blog.content} serializers={serializers} />

<BlockContent blocks={data.news.content} serializers={serializers} />

Sanity – Build the way you think, not the way your CMS thinks

Sanity is the developer-first content operating system that gives you complete control. Schema-as-code, GROQ queries, and real-time APIs mean no more workarounds or waiting for deployments. Free to start, scale as you grow.

Was this answer helpful?