How to combine multiple GROQ queries in a single Sanity client call?
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.newsPostsImportant notes:
Use regular template literals (backticks), not the
groqtagged template literal when combining queries this way. Thegroqtag can cause parsing errors with this syntax.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.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 thread3 replies
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.