React Async/Await Tutorial; In this react guide, we will be learning to send an HTTP request using Fetch API and handle the HTTP response using JavaScript’s Async and Await Syntaxes.
Asynchronous requests are constructive in web development. Also, it provides flexibility in handling responses that may take unexpected time.
The asynchronous paradigm quantifies the efficiency of the application by not hampering the process of other programs.
Now, we will understand in detail what is Async and Await.
The Async is a function bound with a function that returns the Promise object. A Promise object returns the resolve and rejects the response. To pull out the response from the Promise object, we use then and catch methods.
The Await operator is declared with the Promise function and it is always defined inside the async function as a top-level JavaScript module. The Await operator holds the execution of the Promise function as long as the Promise is completely fulfilled.
Pulling out the Promise values from Await function doesn’t require using the then and catch block; we can directly access the properties of the promise response.
React Async Await Handle HTTP Request With API Example
Step 1- Create React Application
Step 2- Install The Bootstrap Module
Step 3- Make The Component File
Step 4- Handle HTTP Response With Async Await
Step 5- Add The Component In App js
Step 6- Run Development Server
Step 1- Create React Application
First of all, we will create a new react app using the given command:
npx create-react-app react-git
Now, we have to enter into the project folder:
cd react-git
Step 2- Install The Bootstrap Module
In this step, we need to install the bootstrap library in React. Below is the command given to be invoked from the terminal window:
npm install bootstrap
Further, we get inside the App.js file where we have to import the bootstrap module CSS:
import "bootstrap/dist/css/bootstrap.min.css"
Step 3- Make The Component File
Here, we have to create a new component in React.
It’s better to keep all the components intact in one place for which we will create a components/ directory.
Then, in this directory, we make a new file Country.js. Below given is the basic structure of a functional component in React:
import React from 'react'
export default function Country() {
return (
<div>
</div>
)
}
Step 4- Handle HTTP Response With Async Await
In the fourth step, we will find out how to make the HTTP request, fetch the data using the REST API and manage the HTTP response with the Async function and await operator.
Now, add the following code in the Country.js file:
import React, { useState, useEffect } from 'react'
export default function Country() {
const [countryItems, initCountry] = useState([])
const fetchData = async () => {
const response = await fetch('https://restcountries.com/v3.1/all')
if (!response.ok) {
throw new Error('Data coud not be fetched!')
} else {
return response.json()
}
}
useEffect(() => {
fetchData()
.then((res) => {
initCountry(res)
})
.catch((e) => {
console.log(e.message)
})
}, [])
return (
<div className="row">
<h2 className="mb-3">React HTTP Reqeust with Async Await Example</h2>
{countryItems.map((item, idx) => {
return (
<div className="col-lg-3 col-md-4 col-sm-6 mb-3" key={idx}>
<div className="card h-100">
<div className="img-block">
<img
src={item.flags.svg}
className="card-img-top"
alt={item.name.common}
/>
</div>
<div className="card-body">
<h5 className="card-title">{item.name.common}</h5>
</div>
<ul className="list-group list-group-flush">
<li className="list-group-item">
<strong>Capital:</strong> {item.capital}
</li>
<li className="list-group-item">
<strong>Population:</strong> {item.population}
</li>
<li className="list-group-item">
<strong>Continent:</strong> {item.continents[0]}
</li>
</ul>
<div className="card-body">
<div className="d-grid">
<a
className="btn btn-dark"
href="{item.maps.googleMaps}"
target="_blank"
>
View Map
</a>
</div>
</div>
</div>
</div>
)
})}
</div>
)
}
Step 5- Add The Component In App js
Now, we will register the Country component in the global app component.
We have to make sure to add the given code inside the src/App.js file:
import React from 'react'
import "bootstrap/dist/css/bootstrap.min.css"
import Country from './components/http/Country'
export default function App() {
return (
<div className="container mt-5">
<Country />
</div>
)
}
Step 6- Run The Development Server
So, we have reached the final step of this guide and now we will start the react app to check the feature on the browser:
npm start
Conclusion
So, we have seen in this React tutorial how easy it is to create user-friendly functionalities in React.
We have learned how to handle HTTP responses using the Async function and Await operator.
Thanks