28
GraphQL Queries - Variables
Real world application requires queries to be dynamic and respond to user input, so we have variables in GraphQL to pass dynamic value and get the response from the server.
Before we jump into the variable definition and use cases, we will get familiar with Operation
If you are just starting your GraphQL journey, read GraphQL Queries - Getting Started before coming to this post
GraphQL allows the user to use shorthand syntax with defining name of the query but the preferred way to define a query name with the query
keyword
query TodoListResult {
todos {
name
completed
created_at
}
}
We have defined Operation name for the above query called TodoListResult
. These names will come in handy when you are debugging your application or logging the data.
There are three operation types in GraphQL
- query - Fetch the data from the database
- mutation - Create/ Modify data in the database
- subscription - Realtime update on changes in data
These operation types form the first part of the operation declaration followed by the name of the operation
{operationType} {operationName} {
}
Variable help in adding dynamic value to the GraphQL Queries. Queries can be reused based on the argument and variables passed. So lets look at an example of using variable inside an operation.
query TodoListResult($count: Int) {
todos(limit: $count) {
name
created_at
}
}
Variables are defined with operation name and their type and then you can use the variable in the operation using the same syntax $count
In this example, we are trying to limit the number of todos returned from the query based on the variable passed into the query. So you can imagine reusing the same query in multiple pages based on your requirement.
When you are calling this query you need to pass the variable.
{
"count": 5
}
Lets look at some practical exercise to get your hands dirty with these GraphQL Variables.
- Creating a query to return the todos from start_date to end_date
- Creating a query to return either
completed
todos ornot completed
todos
If you are unsure where to start follow this tutorial to get started with GraphQL server is a short time using Hasura
Stay tuned by subscribing to our mailing list and joining our Discord community