Graphql - Fetch a Field Conditionally

Graphql - Fetch a Field Conditionally

Imagine that I have a following query (I am using Apollo):

const userQuery = gql`
    query {
      user {
        id
        name
      }
    }
  `;

I want to fetch name field only if some condition is met (let's say variable shouldFetchName is true). How should I approach this and what is the best practice?

1 Answer

You can pass a variable to your query and use a Directive to fetch a field conditionally, like name @include(if: $shouldFetchName).

See the docs for Directives.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.