Using variables in GraphQL queries
To add support for filters and sorting, we need to add variables to our GraphQL query. We can then fill in these variables when executing the query.
Follow these steps to add variables to the query:
- Edit
src/api/graphql/posts.js
and adjust the query to accept an$
options
variable:export const GET_POSTS = gql` query getPosts($options: PostsOptions) {
- Then, pass the
$options
variable to theposts
resolver, for which we already implemented anoptions
argument in the previous chapter:posts(options: $options) {
- Now, we just need to pass the options when executing the query. Edit
src/pages/Blog.jsx
and pass the variable, as follows:const postsQuery = useGraphQLQuery(GET_POSTS, { variables: { options: { sortBy, sortOrder } }, })
- Go to the blog frontend and change the sort order to ascending to see the variable in action!