Lad Who Codes

How a Skip A GraphQL Query Based On Conditions

Posted by Dinesh Verma on Sunday 3 March 2019

GraphQL is an API querying language developed by Facebook. The main advantage of using GraphQL is that it provides a single end-point to be consumed and you can specify what fields you want in the response. This saves the frontend developer from the pain of maintaining and using multiple API end-points.

If you want to learn more about GraphQL, then please refer to the articles published here or watch my video on Why GraphQL is the future of development.

Now, let's get to the point. You . are here because you want to know how can you skip a GraphQL query from executing or how can you make GraphQL query execute conditionally. I recently encountered this situation where I wanted to execute a particular GraphQL query when a condition was met.

Skipping GraphQL queries not only saves us from unrequired network traffic but also can make our components re-usable by conditionally fetching data required to render a component. For example: If you want to create a table to display data of Type X and Type Y, you don't need to create two. different components. Create a single component which takes a property named Type and conditionally fetches data.

Skip a GraphQL query based on condition

The solution is pretty simple. Please follow the code given below.



// Approach 1:
<Query
  query={A_QUERY_THAT_YOU_WANT_TO_EXECUTE_CONDITIONALLY}
  variables={{ something }}
  skip={myCondition}
></Query>


// Approach 2: 
export default compose(
  graphql(A_QUERY_THAT_YOU_WANT_TO_EXECUTE_CONDITIONALLY, {
    skip: (props) => !props.myConditionVariable,
    options: (props) => ( { variables: { id: props.location.state.id } } )
  }))(YourComponent);

And its done. Please let me know if you face any issues :).

Post a Comment