🎁

12 Days of Baddass Courses sale! Get instant access to the entire egghead library of courses and lessons for 58% off.

Runs out in:
15 : 05 : 59 : 27
1×
Become a member
to unlock all features
Autoplay

    Provide Dynamic Arguments in a Apollo Query Component with GraphQL Variables

    Nik GrafNik Graf
    reactReact
    ^16.4.2
    apolloApollo
    graphqlGraphQL
    ^14.0.2
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

    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.

    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.

    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.

    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.

    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.

    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.