Apollo GraphQL Tutorial

In a previous article, we explained the benefits of Apollo GraphQL and why we consider it is the future of APIs. We also listed some reasons why you should be using React for your projects.

Now you’re going to learn how to create your first GraphQL integration with React! For this Apollo GraphQL Tutorial, we’ll be using the public Star Wars API for GraphQL.

Setting up the project

Assuming you have already created a React project (for example, using create-react-app) what you have to do next is add the required libraries for the GraphQL integration. As we’ve seen in the previous article, the two most popular libraries for this are Relay from Facebook and Apollo GraphQL client from Meteor. In this tutorial, we’ll be using Apollo since it’s the friendliest of the two.

Logo Apollo GraphQL Tutorial React

First, we need to install some packages:

Then, we need to create an Apollo GraphQL client to connect with a GraphQL server. In the past, creating a client was a bit difficult, but now we can use apollo-boost, a package that configures all the default settings for the client. The only thing we need to configure is the Server URL. In the future, if you need it, you can override the default setting for the ones you prefer.

Then, we use the Apollo Provider to inject the client into the React app.

Requesting data

After setting the client and using the ApolloProvider, we are ready to perform queries using an Apollo GraphQL component called “Query”. The Query component uses render props to create a request and return some important values, for instance, a Boolean indicating when the query is loading, an error field to show errors and data, and the result of the query, among others.

The queries are written in GraphQL format, so we need to use the “GQL” library to write it in JavaScript. Let’s see how we can get a list with all the Star Wars movies including the titles, episode IDs and directors.

If you wish, you can also perform queries using the client directly. First, you’ll have to use the ApolloProvider component to inject the client object in the desired component.

You can see it in action here:

Updating data

After learning how to request data, we can focus on how to modify it. Similarly to the Query component, Apollo GraphQL provides another component called “Mutation”.

Let’s imagine we want to add a new Star Wars film. In this case, we’ll use the Mutation component passing a GraphQL mutation as props. The render props give us the same information we had with the queries: error, loading and data.

Conclusion

As you can see, the GraphQL integration is really simple. The Query and Mutation components are the best example of how easy it is to perform queries and edits including loading state and error handling with a few lines of code. Apollo GraphQL has done great improvements to make the integrations really straightforward if we compare it with other libraries like redux-sagas.