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.