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 
}

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:

  1. select() evaluates conditions in order and returns the first matching value
  2. Use count() to check if the array has any items: count(*[_type=="user" && references(^._id)]) > 0
  3. The first condition returns your user query with the initial data structure
  4. 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.

count(users) > 0
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 }
}

Solved. Issues with ApiVersion… 🤦

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?