← Back
graphql

Variables in graphql queries

A graphql query looks like this:

query {
todos(limit: 10) {
id
title
}
}

But, do we need to rewrite the query just to change the limit? Of course not:

query($limit: Int!) {
todos(limit: $limit) {
id
title
}
}

When we send the request to the graphql server, we include the query and a variables object:

{ "limit": 10 }

Here's an example with a mutation (insert):

mutation($todo: todos_insert_input!) {
insert_todos(objects: [$todo]) {
returning {
id
}
}
}

And it's variables:

{ "todo": { "title": "Learn GraphQL" } }

More information: https://graphql.org/learn/queries/#variables and https://learn.hasura.io/graphql/typescript-react-apollo/mutations-variables/2-query-variables

🖖