How to conditionally add data to a groq-query if the array is empty
3 replies
Last updated: Sep 12, 2023
AI Update
You can use the select() function in GROQ to handle conditional logic based on whether your array is empty! The select() function works like a switch statement and evaluates conditions in order.
Here's how you can modify your query:
{
"users": select(
count(*[_type=="user" && references(^._id)]) > 0 => *[_type=="user" && references(^._id)] {
// initial data goes here...
_id,
name
},
// fallback data when no users found
*[_type=="fallbackType"][0..10] {
// new data structure here...
_id,
title
}
)
}The key points here:
select()evaluates conditions in order and returns the first matching value- Use
count()to check if the array has any items:count(*[_type=="user" && references(^._id)]) > 0 - The first condition returns your user query with the initial data structure
- The fallback (second parameter) returns alternative data when no users are found
Alternatively, you can use object-level conditionals if you want to conditionally include the entire field:
{
count(*[_type=="user" && references(^._id)]) > 0 => {
"users": *[_type=="user" && references(^._id)] {
// initial data
}
},
count(*[_type=="user" && references(^._id)]) == 0 => {
"users": *[_type=="fallbackType"] {
// fallback data
}
}
}The select() approach is generally cleaner and more efficient since it stops at the first match rather than evaluating all conditions.
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.