Joint session with Vercel: How to build intelligent storefronts (May 15th)

Conditional values in GROQ queries

Only return a value when a condition is fulfilled

By Saskia Bobinska


The query

*[
  _type == "article"
  && (
    !defined(image.altText)
    || (
      count(body[_type == 'image' && !defined(altText)]) > 0
    )
  )
] | order(publishedAt desc) {
  _id,
  title,
  // Condition 1 - document level
 !defined(image.altText) => {
    'image': image.asset,
  },
  // Condition 2 - inside portable text
  count(body[_type == 'image' && !defined(altText)]) > 0 => {
    "bodyImage": body[_type == 'image']
  },
}

Let's assume you want to check which images in your documents have an altText set. These image fields are either on the first document level or in the body field (portable text) as a custom block of type image. To get all documents with images without an altText you can use conditional value fetching in your query.

You can setup conditions using this logic in GROQ:

CONDITION => { VALUES_YOU_WANT},

Contributor

Saskia Bobinska

Senior Support Engineer @Sanity

Germany

Visit Saskia Bobinska's profile