When writing a GraphQL Query
, Mutation
or Subscription
you'll need to pass dynamic data to the query when making the request, to be able to make the app dynamic and respond to different data set.
Basic GraphQL Query
query currentUser {
id
firstName
lastName
email
}
The above GraphQL query will fetch the authenticate the user. This query does not require any argument, due that the server should know how to return the authenticated user. Not a GQL thing, but in general good practice not to allow end-users to call a user endpoint and pass an i.e. user_id.
GraphQL query with arguments, without variables
query {
educators(first: 25, ids: [1,2]) {
edges {
node {
id
firstName
lastName
schools {
id
name
location {
id
name
address
}
}
}
}
}
}
educators
take two arguments first
of type Int and ids
of type ID in a collection. This is how we define the arguments and assign the type to them (note: this could be named anything, it will be the response key name).
The SQL statement that matches the above GraphQL Query
SELECT * FROM educators
WHERE id in (1,2)
LIMIT 10;
GraphQL query with variables
Now the same as the query above, with dynamic variables that we can pass to the query in execution time. This is great now because now this query can be reuse around multiple clients.
query educators($first: Int, $ids: [ID!]) {
educators(first: $first, ids: $ids) {
edges {
node {
id
schools {
id
name
location {
id
name
}
}
}
}
}
}
Varaibles definition
{
"first": 25,
"ids": [1,2]
}
i.e. with Apollo Client hook example
import { useQuery } from '@apollo/client'
// GET_EDUCATORS_QUERY is the above query
useQuery(GET_EDUCATORS_QUERY,
{ variables: { first: 25, ids: [1,2] } }
);
Conclusion
To help explore GraphQL Variables, you can use the GraphQL Playground. GraphQL variables give the flexibly of sending dynamic variables to the query and at the same time the ability to use the query in multiple clients that require to fetch the same data.
Top comments (0)