Instructor: Here, you can see a React app initially created using createReactApp. I simplified the content and replaced the styles. In order to get started with Apollo client, we run npm install to add the following NPM packages, GraphQL, Apollo Boost, and React Apollo.
The GraphQL package is needed for certain features, like parsing GraphQL queries. Apollo Boost is a package coming with a well-configured Apollo, in order to get started quickly. Last, but not least, React Apollo.
It integrates Apollo with React by providing multiple components and utils. Then we import the Apollo client from Apollo Boost, and instantiate a new client. The only mandatory option we need to provide is the URI for our GraphQL endpoint.
In this case, we are using localhost on port 4,000, since there, I already have a GraphQL server running. Let's verify that our client works as expected by requesting data from our GraphQL endpoint using a query.
It expects an object containing at least a query property, and write one using a template tab notation. What to fetch now? Our back end is a cookbook containing recipes. To get started, we can create all recipes.
For each of them, we request the ID and the title. We import the GraphQL type library. Once the query's resolved, we print out the results. As you can see, once we loaded the page, the query was executed, and our result logged in the console.
So far, so good. Since we have React Apollo available, let's look into how we can set it up. We import the Apollo provider from React Apollo, and use it inside our render function. The provider requires an instantiated Apollo client.
In our case, we take the one we already initialized. Once set up, the Apollo provider now passes the client down the rendering tree via React's context feature. Using an Apollo consumer, we can leverage this setup to use the client for our queries deeper down in our React rendering tree. In this case, we take our existing query and run it inside the Apollo consumer render prop.
To comply to React's API expectations, we return null. As you can see, we still get back some results. While Apollo consumer can be useful in some cases, most of the time, you will be using the query, mutation component, or higher order components, all shipping with React Apollo.