Build Client Side GraphQL React Application using GitHub GraphQL API (Part-1)
Tags: react, redux, graphql, javascript
Published: 2020-03-27 07:00:36

In this series of articles, we will build a react client app which will interact with GitHub GraphQL API. 
At the end of this series you will create an app with below features:

1. Validate GitHub token access of a user
2. Search the Public Repository which are in GitHub
3. Able to Star and Watch your favourite public repository
4. Show Star, Watch and Total public repository count for search results. 

You can find the code repository here: {% github Heet1996/ReactApp %}

Final source code : {%github Heet1996/GitHubApi %} 

You can find the app here: [GitHub Repo Finder](https://githubrepo-cc932.firebaseapp.com/). *Before reading further I would highly recommend you to have a tour of app.* 
*** 
##Note: Please ensure that you have a fair understanding on below points. It will help me to make you understand about this article.
1. [React] ( https://reactjs.org/): 
This tutorial assumes that you have a good experience on React. Please check-out their docs if you want to learn react.
2. [React-Redux]( https://react-redux.js.org/): 
We are using this cool library for store management. Please check-out their docs if you want to learn react-redux.
3. [React-Router](https://reacttraining.com/react-router):
To create single page application, for easy and protected routes.
4. [Redux-thunk]( https://github.com/reduxjs/redux-thunk): 
To perform asynchronous updates/ actions on redux store. I have chosen redux-thunk but redux-saga is also a great alternative.
5. [GraphQL]( https://graphql.org/): 
Since we are using GitHub GraphQL API I highly recommend you to know this sexy cool library. Basics is enough rest we will cover in this article.
6. [NPM]( https://www.npmjs.com/):
I will be using npm package manager throughout this series if you want to learn more check their docs. 
7. [Axios (Http Client)]( https://github.com/axios/axios):
To call GitHub Graphql endpoint we will be using Axios. You can use Apollo Client as well.      

***
Well lot of pre-requisites and many things to digest. So, let’s begin by setting up our project 😊 
 
###Step 1: Create a React App.
Create your react project with help of below command. 
``` 
npx create-react-app “Your Project Name”
cd “Your Project Name”
npm start 
```

After creating the app, start your app. You can run `npm start` command and this should bootstrap your app without any error.

###Step 2: Create a Landing Page (Optional)
Well this is optional but I would recommend you to build this so that you can give gist to your user about what these app does.
Create a src/component and src/container folder so that you can distinguish your [stateless from state components]( https://code.tutsplus.com/tutorials/stateful-vs-stateless-functional-components-in-react--cms-29541).  
You can find the code here: [Landing Page](https://github.com/Heet1996/ReactApp/tree/master/src/components/Home)

![alt Home Page](https://i.ibb.co/rd3Q72C/Home.png)

###Step 3: Getting started with GitHub GraphQL Api
To use GitHub's GraphQL API, you need to generate a personal access token on their website. The access token authorizes users to interact with data, to read and write it under your username. Follow their [step by step instructions]( https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line) to obtain the personal access token, and be sure to check the necessary scopes (permissions) for it, as you will need them to implement a well-rounded GitHub client later. After generating the access token, you can validate your token with the help of [GraphIQL application](https://www.electronjs.org/apps/graphiql).
####Interacting with GitHub GraphQL Api using GraphIQL application.
#####Add your GraphQL Endpoint:
![alt text](https://i.ibb.co/Y36zrwk/Capture2.png)
#####Set Your Header Field:
In the next step, we add a new header with a name and value to your GraphiQL configuration. To communicate with GitHub's GraphQL API, fill in the header name with "Authorization" and the header value with "bearer [your personal access token]". Save this new header for your GraphiQL application. Finally, you are ready to make requests to GitHub's GraphQL API with your GraphiQL application.

![alt text](https://i.ibb.co/wyknZ1P/Capture1.png)

 
###Step 4: Validate the User Token

![alt Validate Your Token](https://media.giphy.com/media/kaTAZfXvSVuYdbXsD2/giphy.gif)

In this section we will write a logic to validate the access token which you have generated above. In general, our objective is that a user cannot proceed further if they have an invalid access token. Moving further this validation will help us to make our routes protected.
Create a src/containers/TokenValidator/[TokenValidation.js]
(https://github.com/Heet1996/ReactApp/blob/master/src/containers/TokenValidator/TokenValidation.js)
##### Handling the user input

```
import * as actions from '../../store/actions/index';

class TokenValidator extends Component
{
    state={
        token:''
    }
    handleForm=(e)=>{
        e.preventDefault();
        this.props.tokenValidator(this.state.token);
    }
    inputChangeHandler=(e)=>this.setState({token:e.target.value});
        
    
    render()

```
#####State of the Token
Here we can use token as a state to store the access token given by user.   
######1. handleForm 
This function executes when user submits the token (we will talk about inner implementation shortly)

######2. inputChangeHandler
 Changes the state of token on every input of a user 
##### Handling the actions 
```
const mapStateToProps=(state)=>{
    return {
        token:state.tokenValidator.token,
        loading:state.tokenValidator.loading,
        error:state.tokenValidator.error
    }
}
const mapDispatchToProps=(dispatch)=>{
    return {
        tokenValidator:(token)=>dispatch(actions.tokenValidator(token))

    }
}
export default connect(mapStateToProps,mapDispatchToProps)(TokenValidator);

```
Here comes the react-redux to the rescue where we can use valid token across the application. As notice above whenever user submits the token `this.props.tokenValidator(this.state.token)` is call which dispatches `tokenValidator` action to update the reducer and also validate our token.
#### Our Redux Store and Actions
Before heading further, I would recommend you to create a folder structure as shown below for your redux store. *You may choose to follow other folder structure but keep a habit of best practices so that you can clearly distinguish your actions and reducer.*

![alt Folder Structure](https://i.ibb.co/nLm9bKr/folder-Structure.png)
##### Different Action Types 
We cannot update redux store directly and it is done through reducers. With different actionTypes we will trigger our actions and ask reducer to update the state/store accordingly.     
I always keep my action creator and action type file separated so that it is easy to maintain and readable.
I will not be able to explain all the code in details. You can find the code for this section below:

a.	[Reducer] (https://github.com/Heet1996/ReactApp/blob/master/src/store/reducers/tokenValidator.js)
b.	[Actions]
(https://github.com/Heet1996/ReactApp/blob/master/src/store/actions/tokenValidator.js) 

##### Our first Reducer (tokenValidator.js)
Let’s see what all synchronous actions do we have:
1.	tokenValidStart - First action to dispatch whenever async action is call
2.	tokenValidSuccess- If our http request is complete and promise is resolve than success action is dispatch.
3.	tokenSetter- Once the promise is resolve we will set the token state in our redux store only if our response status is 200.   
4.	tokenValidationFail- If our promise is rejected then failure action is dispatch.  
5.	tokenInvalid- If our token is not valid than this action is dispatch which updates error state to ‘Invalid’ in our redux store. This attribute will help us to identify whether token is valid or not.   
```
export let tokenValidator=(token)=>(dispatch)=>{

    dispatch(tokenValidStart());
    axios.post(`https://api.github.com/graphql`,{
        headers:{
            'Authorization':`bearer ${token}`
        }
    })
    .then((res)=>{
        dispatch(tokenValidSuccess());
        if(res.status=='200')
        dispatch(tokenSetter(token));
        
    })
    .catch((err)=>{
            
            if(err.response)
            {
                if(err.response.status=='401')
                dispatch(tokenInvalid());
                else dispatch(tokenValidationFail(err)); 
            }
            else dispatch(tokenValidationFail(err)); 
    })

}

```
 As you can see above, we have created a redux thunk where we accept token as a parameter (refer your Dispatch props in TokenValidation.js file) and also dispatching multiple synchronous actions which we have discuss above. 
That’s it this is our reducer for token validation and different actions for our react-redux application.
Congratulations! Till now we have covered below feature:
* Validate GitHub token access of a user.

In my upcoming articles I will cover the features given below with some basics of GraphQL as well.
* Search the Public Repository which are in GitHub
* Able to Star and Watch your favourite public repository
* Show Star, Watch and Total public repository count for search results.

Please leave your comments below regarding these article and stay tuned for Part 2! :-)

#####Stay Home, Stay Safe :)