# Making @skip and @include Dynamic

Directives @skip and @include receive the condition to evaluate through argument "if", which can only be the actual boolean value (true or false) or a variable with the boolean value ($showExcerpt), as in this query:

query GetPostTitleAndMaybeExcerpt(
  $showExcerpt: Bool!
) {
  post(id: 1) {
    id
    title
    excerpt @include(if: $showExcerpt)
  }
}

What about executing the "if" condition based on some property from the object itself? For instance, we may want to show the excerpt field based on the Post object having comments or not.

Well, directive @export makes this possible. For this query:

query GetPostHasComments(
  $id: ID!
) {
  post(id: $id) {
    hasComments @export(as: "_hasComments")
  }
}

query ShowExcerptIfPostHasComments(
  $_hasComments: Boolean = false
) {
  post(id: $id) {
    title
    excerpt @include(if: $_hasComments)
  }
}

...the response will include field excerpt or not, depending on the queried post having comments or not.

Let's check it out. Running the query for post with ID 1 produces this response:

The response includes field

Running the query for post with ID 1499 produces this response:

The response includes field

As it can be seen, @include became dynamic: the same query produces different results based on some property from the queried object itself, and not from an external variable.

This features works only when the exported variable (in this case, $_hasComments) concerns a single value, but not for lists. This is because the algorithm evaluates the if condition for all objects in the list in the same iteration, overriding each other; then, when this result is checked to perform the @skip/@include validation in some later iteration from the algorithm, only the value from the last object in the list will be available.

Last Updated: 8/11/2020, 11:12:50 AM