Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Fetch Data using the Apollo Query Component


    In order to display data we first need to fetch it. The Query component allows us to describe which data we are interested and automatically handle the fetching of our data. Once we received the data we can render it using React. Since the Query component handles the data fetching we need to make sure we properly deal with the cases of a loading state as well as when the receive Errors from the GraphQL API. In this lesson we will cover both.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    Instructor: The query component allows us to fetch data, and provides the data as a render prop. We import the query component from react-apollo, and use it in our JSX tree. The query component has one mandatory prop, a query.

    For the query, we're again going to use the GraphQL tag with a query string inside it. So far, so good. The query component's child must be exactly one function. It receives a query result object, containing the data.

    This data object initially is empty, but once loading finished, it contains the result of our query. Without the recipes attached to the data, we return null. Once we receive the recipes, we can render them.

    It works like a charm. There's one gotcha, though. At the moment, we don't why our recipes are undefined, because they could be still loading, or an error could have occurred. In order to help with that, the query component exposes two more properties, loading and error.

    It allows us to render a different UI depending on the state of the query. If we refresh the web app, we can see our loading and our rendering, until loading is finished and the actual data arrived. In order to test the error inaudible , we simply stop the server. As expected, we now see the error case being rendered.

    Before I wrap up this lesson about the query component, we want to refactor the code a little bit. First, we're going to extract the query component, fetching and rendering the recipes into its own recipes component.

    Of course, we also need the required imports. Then we can use the recipes component inside our application. As you can see, our recipes still render, and our refactoring worked. Next up, we extract the query into its own constant.

    While this totally depends on your preferences, I personally find the code easier to parse if the query is separate. In addition, you can extract the query into a separate file inside, or possibly even outside, the component folder if you reuse it multiple times.