Unforgiven
Unforgiven

Reputation: 331

Gatsby: Allow non-existing fields in GraphQL Queries

I'm using Gatsby with the Wordpress source plugin. So far so good. But the thing is I am querying fields that might or might not be there, in this case, the featured image of a post. Here is my query:

{
allWordpressPost(sort: { fields: [date] }) {
      edges {
        node {
          title
          excerpt
          slug
          featured_media
          better_featured_image {
            wordpress_id
            alt_text
            caption
            description
            media_type
            post
            source_url
          }
        }
      }
    }
}

It works well when the featured image is set, but fails miserably otherwise. And so my question: Is there any way in GraphQL to query an optional field? To add a default value to a required field? I am all too new to GraphQL so I'm not even sure that's possible at this point. Thank you.

Upvotes: 1

Views: 2066

Answers (1)

chmac
chmac

Reputation: 12625

This article explains the back story, but in short, you need to make sure that at least 1 of your WordPress posts has the featured image. Then the better_featured_image field will always exist.

In javascript, if you try to access allWordpressPost.edges.node.better_featured_image.wordpress_id and better_featured_image does not exist, you'll get a syntax error.

Without knowing what "fails miserably" specifically means, not sure what else to suggest.

Upvotes: 2

Related Questions