✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

How to conditionally add data to a groq-query if the array is empty

3 replies
Last updated: Sep 12, 2023
Hello, Im trying to do a condition inside my groq-query. Anyone that knows how I can check if the array is empty and add other types of data?
Example:

"users" : *[_type=="user" && references(^._id)]  { 
    initial data goes here...
},
users.length === 0 => {
   new data goes here if we could not get any users 
}

Sep 12, 2023, 11:51 AM
count(users) > 0
Sep 12, 2023, 12:38 PM
Thanks, but I still cannot get it work for some reason. Can it be some issues with the time it takes to actually fetch the data inside users? Pasting the “full” query here if that can clarify

`*[_type=="docs" && uuid == $uuid][0] {
  _id,
  "users" : *[_type=="user" && references(^._id)] {
    initial data... 
   },
 count(users) > 0 => { ...more data }
}

Sep 12, 2023, 1:00 PM
Solved. Issues with ApiVersion… 🤦
Sep 12, 2023, 1:25 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?