Fetch Data using the Apollo Query Component

Nik Graf
InstructorNik Graf
Share this video with your friends

Social Share Links

Send Tweet

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.

Instructor: [00:00] 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.

[00:15] 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.

[00:33] 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.

[00:47] 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.

[01:15] 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.

[01:44] 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.

[02:03] 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.

[02:30] 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.