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.jsand adjust the query to accept an$optionsvariable:export const GET_POSTS = gql` Â Â query getPosts($options: PostsOptions) { - Then, pass the
$optionsvariable to thepostsresolver, for which we already implemented anoptionsargument in the previous chapter:Â Â Â Â posts(options: $options) { - Now, we just need to pass the options when executing the query. Edit
src/pages/Blog.jsxand 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!