👋 Next.js Conf 2024: Come build, party, run, and connect with us! See all events

Using defined() function to check for null fields in Sanity query

6 replies
Last updated: Mar 8, 2022
defined(Field) => Field. inside my query after console logging totally disappeared. Even if I do have one field which is not empty. Any idea?
Mar 5, 2022, 8:41 AM
user A

Video enabled, poster, platform and url by default return null. I have one article which has these values. But I have tried like checking to see if one of those fields is defined else don’t show it in the console log. But defined just removes the all the video fields even with one post which has a video.


"featured": *[_id == "featuredSettings"][0] {
    featuredArticles[] -> {
      title,
      body,
      publishedAt,
      author -> {
        name,
        featuredImage,
      },
      videoEnabled,
      videoPoster,
      videoPlatform,
      videoURL,
      'slug': slug.current,
    }
  },

Mar 5, 2022, 10:30 PM
How are you trying to use
defined()
? Does it look like this?

"featured": *[_id == "featuredSettings"][0] {
  featuredArticles[]-> {
    title,
    body,
    publishedAt,
    author-> {
      name,
      featuredImage,
    },
    defined(videoEnabled) => videoEnabled,
    defined(videoPoster) => videoPoster,
    defined(videoPlatform) => videoPlatform,
    defined(videoURL) => videoURL,
    'slug': slug.current,
  }
},
Mar 5, 2022, 11:03 PM
Exactly when I console log this QUERY the fields are not there. While 1 post does have all the fields and is published
Mar 5, 2022, 11:04 PM
I believe the API requires the return to be wrapped in curly braces. Could you try this?

"featured": *[_id == "featuredSettings"][0] {
  featuredArticles[]-> {
    title,
    body,
    publishedAt,
    author-> {
      name,
      featuredImage,
    },
    defined(videoEnabled) => {videoEnabled},
    defined(videoPoster) => {videoPoster},
    defined(videoPlatform) => {videoPlatform},
    defined(videoURL) => {videoURL},
    'slug': slug.current,
  }
},

Mar 6, 2022, 4:10 AM
user A
Thanks for the late reply. This does the trick. Could you explain me why it works with curly brackets only?
Mar 7, 2022, 5:26 AM
Hi Nino. This conditional form is syntactic sugar for a spread select function, as we see toward the bottom of the code block here . The first example in that block can use strings on the right side of the pair because there is a key to which it’s assigned:
popularity
. With the shorthand conditional, those curly braces are mandatory as we’re not returning a string value to a key, but one or more attributes back to the projection. Hope that makes sense, and glad it’s working for you.
Mar 8, 2022, 12:27 AM

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?