Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GraphQL - fetch a field conditionally

Tags:

graphql

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?

like image 857
Adam Wolski Avatar asked Nov 14 '17 10:11

Adam Wolski


Video Answer


1 Answers

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.

like image 171
Andrija Ćeranić Avatar answered Oct 08 '22 19:10

Andrija Ćeranić