With more features being added to Javascript, I decided to try using async await. It was easy to use and more importantly made the code easier to read. On my personal site the list of projects that are displayed are actually from the Github API. In this post I’ll go through creating a React project from scratch, requesting data from the Github API, and then using components that display the API data. If you are already familiar with creating React projects, just skip ahead to where we write the project list component.

Creating our application & adding dependencies

To create our application you can either use npm or yarn, in my example I will be using npm. With the command line / terminal:

Navigate to where you want your project to be Create a folder and navigate into that folder Run npm init -y to create an npm project with all the defaults, which will be fine for our purposes Run npm install react react-dom axios --save. Axios will be used to make our API request Run npm install webpack webpack-dev-server html-webpack-plugin babel-core babel-loader babel-preset-es2015 babel-preset-react --save-dev All of these are used to build our project

Writing the webpack and babelrc files

Open the folder that you created in your favorite text editor / IDE, then create two files: webpack.config.js and .babelrc . The webpack.config.js file just needs an entry point, output, and modules (which hold our rules) but we are also going to add the html webpack plugin. The html webpack plugin generates an html file for you that includes all your webpack bundles.

webpack.config.js

var HtmlWebpackPlugin = require('html-webpack-plugin')

var path = require('path') module.exports = {

entry: './index.js', // entry point of our application

output: {

filename: 'bundle.js', // the name of the bundled file

// path of the bundled file

path: path.resolve(__dirname, 'dist')

},

module: { // rules for bundling our files

rules: [

{

test: /.js$/, // what to look for

exclude: /node_modules/,

use: [

'babel-loader'

]

}

]

},

plugins: [

new HtmlWebpackPlugin({

title: 'Async Await With React',

template: 'index.html',

})

]

}

.babelrc

{

"presets": ["es2015", "react"]

}

Writing our main App component

Create three files, App.js, index.js, and index.html in the root of our project. In a real project you will most likely have a src folder and more but we don’t need them here.

index.html — the template used for our webpack.config.js file

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial- scale=1.0">

<title>Async Await with React</title>

</head>

<body>

<div id="root"></div>

</body>

</html>

index.js — the entry point of our application

import React from 'react'

import { render } from 'react-dom'

import App from './App' render(<App/>, document.getElementById('root'))

We only need to import React, render, and our App component, which we’ll make next. The render method takes the component from the first argument and renders it into the DOM element specified in the second argument.

App.js

import React, { Component } from 'react' export default class App extends Component {

constructor() {

super()

}

render() {

return (

<h1>React App</h1>

)

}

}

We are only displaying an h1 tag of “React App” just to see if everything works correctly. Lastly we will want to write an npm script that makes our development much easier. In your package.json file add a script called “dev”, with the following:

"scripts": {

"dev": "webpack-dev-server --hot"

}

NOTE: This is not the entire package.json file. This is only a snippet showing the scripts field

All the bold lines of code are new additions from what we had before.This script will start a development server for us and will update our application in the browser whenever we save changes to our files. To start our application, go to your terminal / command prompt navigate to the root directory of the project. Then run the command npm run dev . The output should look similar to this:

In your browser go to where your project is running, in my case it was http://localhost:8081/. Your browser should only be displaying “React App” in bold, if it does you are good to move on!

Writing the ProjectsList component

Create just one more file, ProjectsList.js. ProjectList is a stateless component that is only responsible for displaying our repositories. The App component is responsible for requesting from the Github API.

App.js

import React, { Component } from 'react'

import axios from 'axios' import ProjectList from './ProjectList'

var GH_TOKEN = 'Your-Token-Here' export default class App extends Component {

constructor() {

super() this.state = {

repos: [],

btnPressed: false,

}

} async getRepos() {

var axiosInstance = axios.create({

baseURL: 'https://api.github.com/user',

headers: {

'Authorization': `token ${GH_TOKEN}`

}

})

try {

let response = await axiosInstance.get('/repos')

this.setState({

repos: response.data,

btnPressed: true

})

} catch (err) {

console.error(err)

}

} displayApp() {

if (this.state.btnPressed)

return <ProjectList repos={this.state.repos}/>

else

return <button onClick={this.getRepos.bind(this)}>Get

Repos</button>

} render() {

return (

<div>

<h1>React App</h1>

{this.displayApp()}

</div>

)

}

}

You will need to get an access token from Github, you can find information on getting one, here. We also need to bring in our ProjectsList component which will display our repositories. At the start of our application we have no repositories and the button to get the repositories has never been clicked, which is reflected in “this.state” in the constructor. We use the state of the main App component to determine what to initially display, which is just a button under the header. Since the getRepos function has the code responsible for making the asynchronous API request we need to put the async keyword in front of it. We then wrap the code that does the actual requesting in a try block and make sure to add the catch block to catch any errors. The await keyword needs to be placed in front of the code that will return a promise. So let response = await axiosInstance.get('/repos’) means we are waiting for the promise to resolve then placing it into the variable, response. Lastly we update our state by changing our btnPressed to true and adding the repos from Github to the repos in the state of our application. Notice that we pass the repos down as props to the ProjectsList component in our displayApp function.

ProjectsList.js

import React, { Component } from 'react' const ProjectsList = ({repos}) =>

<div>

<h2>Project List</h2>

<ul>

{repos.map((repo, i) =>

<li key={i}>Name: {repo.name}, Main Language: {repo.language}

</li>

)}

</ul>

</div> module.exports = ProjectsList

The ProjectsList component uses the repos that were handed down as props and maps through them to display the data with li elements. We know that name and language are actual fields because of the documentation, check it out here. If you followed along you should see something like this after you press the button. 💃

P.S. Follow me on twitter