Provide Dynamic Arguments in a Apollo Query Component with GraphQL Variables

Nik Graf
InstructorNik Graf
Share this video with your friends

Social Share Links

Send Tweet

GraphQL supports parameters for queries via variables. They allow us to supply dynamic arguments. Often we want these variables to be dependent on decisions made by a User. In this session we are going to walk through how to implement a filter variable based on a UI checkbox element using Apollo's Query component.

Instructor: [00:00] In order to filter for vegetarian recipes, our recipes query accepts a Boolean argument, vegetarian. Once the page reloads, we can see that now, only vegetarian recipes show up. In this lesson, we want to make the vegetarian argument dependent on a checkbox, which can be controlled by a user.

[00:21] Before we do so, let's kick off with some basics. Using the GQL template tag, we can ensure that a query must be provided with certain variables. We first declare a name for a specific query, using the syntax query, and then the name.

[00:36] Then we indicate that the variable vegetarian is a Boolean. By adding an exclamation mark, we declare this variable as mandatory. In order to provide the query component with variables, we simply add another prop, variables.

[00:52] It accepts an object with the query variables as key-value properties. In our case, we set vegetarian to true. Now, we refresh the browser, and verify that we still only see vegetarian meals. Next up, we want to implement the checkbox UI, and keep track of its state.

[01:12] To do so, we add state to our React component, and set the vegetarian property to false by default. We then use the vegetarian state for our query variable. Then we use React's fragment component to wrap our existing UI.

[01:33] This way, we can keep our existing code and prepend the filter UI. We add a checkbox and a label. The check prop is again based on this.state.vegetarian, and on onChange, we're going to invoke this.updateVegetarian, which we yet have to implement.

[02:00] We implement our missing function, updateVegetarian. Here, we destructure the incoming event to extract the checked value, and use it to update the state. Let's verify our code. As you can see, we render the checkbox and the list. Depending if the checkbox is checked, we either see all meals, or only the vegetarian meals.