GraphQL Apollo Client in React: Build a GraphQL Client React-App step by step

Rany ElHousieny
Nerd For Tech
Published in
8 min readJan 4, 2021

In the following articles, I will explain step by step how to build a GraphQL React App using Apollo Client's latest release. It will be a compilation of a few articles / Steps

The full code can be found at

  1. Step1: Setup the main project and query https://www.linkedin.com/pulse/graphql-apollo-client-react-step1-setting-up-base-rany/

2. Step 2 — Query and present the data using Query from react-apollo: https://www.linkedin.com/pulse/graphql-apollo-client-react-step-2-query-present-rany/

3. Step 3 — Print list from a GraphQL Query: https://www.linkedin.com/pulse/graphql-apollo-client-react-step-3-query-present-rany/

4. Step 4: GraphQL Apollo Client in React: Step 4 — Passing Variables: https://www.linkedin.com/pulse/graphql-apollo-client-react-step-4-passing-rany-elhousieny-phd%E1%B4%AC%E1%B4%AE%E1%B4%B0/

==================================

Step1 -Setting up the base project

In this short article, I will explain how to interact with GraphQL API from React using Apollo Client. I will build a very simple app (final code can be found at https://github.com/ranyelhousieny/GraphQL_ApolloClient_React/tree/master/fetch-data ).

Since this is more focused on Front-End, I will use a public GraphQL API to fetch data (https://countries.trevorblades.com/). I will not explain GraphQL server-side, GraphQL basics, or React basics. I assume you know GraphQL and React basics and know how to create an app using create-react-app. This article will show how can you fetch data from a GraphQL API using Apollo Client.

Before we start with the code, let’s understand how React interacts with GraphQL and Apollo. Apollo client where we can get from apollo-client is not aware of React. The job of Apollo Client is to interact with a GraphQL server and store data in Apollo Store (similar to Redux store :)). However, we link React to Apollo client with ApolloProvider from react-apollo. ApolloProvider will wrap our React App and allow all children Apps to interact with the store. If you worked with Redux, before, you will find this familiar.

1. Create a react project using npx create-react-app <app name>

or you can clone my project and follow along

git clone https://github.com/ranyelhousieny/GraphQL_ApolloClient_React.git

2. import Apollo React Provider on src/index.js

3. import Apollo Client to src/index.js

4. import and initialize InMemoryCache and HttpLink

4. Create the basic client

Starting Apollo 2.0 you have to initialize the client using cache and link as follows:

5. Install dependencies

npm install apollo-client react-apollo apollo-cache-inmemory apollo-link-http — save

6. wrap the React app inside the Apollo provider

Here is index.js so far:

https://github.com/ranyelhousieny/GraphQL_ApolloClient_React/blob/master/fetch-data/src/index.js

You can start your web app using npm start to see on the screen what you are building. I changed App.js to be as follows (Optional for now) https://github.com/ranyelhousieny/GraphQL_ApolloClient_React/blob/master/fetch-data/src/App.js

You can see the output on the browser by going to https://localhost:3000

Add the URL for the GraphQL server

Now, let’s add the URL for the GraphQL server to package.json https://github.com/ranyelhousieny/GraphQL_ApolloClient_React/blob/master/fetch-data/package.json

“proxy”: “https://countries.trevorblades.com/"

Get the query from https://countries.trevorblades.com

Now, let's go to https://countries.trevorblades.com and try a query to put it in the code

try the following query as shown above on the left side and click the arrow to see the result on the right side

query{ country(code:"US"){  code  name }}

Add query to the code

Let’s add the query to the code and print the result to console for now

  1. import gql
import gql from 'graphql-tag';

2. add the query you copied to the client as shown below (please note the symbol ` where you write the query in between )

You can verify the result on the console from the browser as follows (I am assuming that you still have npm start running)

Step 2 — Query and present the data using Query from react-apollo

In the previous step (https://www.linkedin.com/pulse/graphql-apollo-client-react-step1-setting-up-base-rany/ ) we created the base project and issued a GraphQL query to get one country. I implemented everything in index.js and printed the result to the console for simplicity. in this article we will present the result of the query on the browser.

1. Add the query to a global variable in App.js

2. Print the result to the screen

we will make use of Query from react-apollo

import { Query } from ‘react-apollo’;

Full code can be found here https://github.com/ranyelhousieny/GraphQL_ApolloClient_React/blob/master/fetch-data/src/App.js

Step 3 — Query and present the List of item from data using Query from react-apollo and map

In the previous articles, we created a react app and got the data from GraphQL. We only printed one Country.

  1. https://www.linkedin.com/pulse/graphql-apollo-client-react-step1-setting-up-base-rany/
  2. https://www.linkedin.com/pulse/graphql-apollo-client-react-step-2-query-present-rany/

Let’s print a list of countries with a “Detail” Link (I am not using any css yet so it is simple ul). Code at: https://github.com/ranyelhousieny/GraphQL_ApolloClient_React/blob/master/fetch-data/src/components/CountriesList.jsx

The final page will look as follows:

1. The query is straight forward copy from the site

2. CountriesList component

Let’s create a new Component under the components folder for the countries list and add the query as we have done before

The only new thing is that we will receive and array and use map to print each item

We will call this component from App.js

Step 4 — Passing Variables

First, let’s add a route to switch to a new page for details

index.jsimport { BrowserRouter, Route } from 'react-router-dom';....ReactDOM.render(
<ApolloProvider client={ client }>
<BrowserRouter>
<Route exact path='/' component={ App } />
<Route exact path='/country/:country_id' component={ Country} />
</BrowserRouter>
</ApolloProvider>,
document.getElementById('root')

Then add route under each country on the list (CountriesList.jsx)

<Link to={ `/country/${country.code}` } >Details</Link>

Create a new functional component Country.jsx and import gql, Query as before

import React from 'react';
import gql from 'graphql-tag';
import { Query } from 'react-apollo';

We received the country code as params. Let’s print it to the console to see how it looks like

const Country = ( props ) => {
const { country_id } = props.match.params
console.log( "props", props, " Country Id = ", country_id );

As you can see, above, it is an object that has another object name “match”. Inside match another object named “params”, that has the variable we are looking for “country_id”

Let’s extract country_id as follows:

const { country_id }  = props.match.params

now we need to add it to the query. As usual let’s try it on the server first and copy from there (https://countries.trevorblades.com/ )

You will notice that we added a mandatory variable “$id” next to the query. All variables in GraphQL query starts with $. It is of type ID and the ! next to it means it can’t be null

query($id: ID!){

Also, we need to provide code to identify which country, which we will get it from the variable $id

country(code:$id){

Note the variables at the bottom where we pass the value of this variable

{
"id": "US"
}

Copy the query and add it to the code

const QUERY = gql `query ($country_id: ID!) {
country(code:$country_id){
code
name
native
}
}`

Now You will need to pas it as Variables in Query

<Query query={ QUERY } variables={ { country_id } }>

Here is the full file https://github.com/ranyelhousieny/GraphQL_ApolloClient_React/blob/master/fetch-data/src/components/Country.jsx

Here is the output on the browser

By: Rany ElHousieny

--

--

Rany ElHousieny
Nerd For Tech

https://www.linkedin.com/in/ranyelhousieny Software/AI/ML/Data engineering manager with extensive experience in technical management, AI/ML, AI Solutions Archit