REACT WITH APOLLO GRAPHQL

GraphQL is a query language used by Facebook to extract data from a graph database and it is a powerful alternative to REST. GraphQL offers a clear abstraction layer between servers and clients, than cannot boast REST, which offering solutions narrow applicability. GraphQL can make your code much easier to maintain and also speed up app development.

This is tutorial about getting started with GraphQL on the frontend. We would use this endpoint https://graphql-pokemon.now.sh/ to fetch pokemons. By the end of it you’ll have a very simple React UI that loads its data with GraphQL and looks something like this:

So, let’s start!

1. Getting set up

We are going to use create-react-app, so, at first, we need install that:

We need to create app with create-react-app:

Let’s make sure it’s working:

When it all right you should see in your browser the next:

2. Writing components

To keep this tutorial short, we’ll only build a simple carousel view. Let’s change a few things in App.js. Create Panel.js and paste this (we would use some modules to develop faster):

Create-react-app sets up hot reloading for you, so as soon as you save the file, the browser window with your app should update to reflect the changes:

Let’s write two components that show one pokemon and carousel of pokemons on each tabs:

3. Try GraphQL queries

Before using graphql query we can easy try it. Let’s go to https://graphql-pokemon.now.sh/ and try to get first 3 pokemons:

Pretty easy, isn’t it? Let’s do another one to take one pokemon by name:

We would use similar queries for our app.

4. Wiring your component together with the GraphQL query

Now we can hook up component with Apollo Client. Let’s install react-apollo to get GraphQL into our app. React-apollo lets you decorate components with graphql to get your GraphQL data into the component without efforts.

Now we need add several imports at the top of App.js and create an instance of Apollo Client

and decorate Pokemons with a GraphQL HOC:

When wrapped with the graphql higher order component, our Pokemons component will receive a prop called data, which will contain pokemons when it’s available or error when there is an error. In addition data also contains a loading property, which is true when Apollo Client is still waiting for data to be fetched.

Finally, we have to add our Panel inside our App’s render function. In order to make an instance of Apollo Client available to the component we just created, we also wrap our top-level app component with ApolloProvider, which puts an instance of the client on the UI.

Now your app’s component should look like this:

That’s all. If you don’t want to use existing API, you can mock it using graphql-tools and apollo-test-utils from NPM

No responses yet