Create Asynchronous HTTP GET Request in React with Axios

React Asynchronous Get request tutorial; In this comprehensive post, we will teach you how to make asynchronous HTTP GET request in React application. To handle the Get request in React, we will use the Axios package.

We will also show you how to use async/await methods in React application to handle HTTP get request.

HTTP headers are the additional information that we pass to quantify the request process. It is a sort of significant information passed along with the request arsenal; this guide will also demonstrate how to set HTTP headers with Axios get request.

Axios offers a facile solution and makes your life easy when it comes to handling HTTP requests. It is a promise-based HTTP client package mainly used to make HTTP requests and deal with the request-response.

It is a free library, One of the great things about Axios is that it tightens your web security and comes preloaded with security features like CSRF (Cross-Site Request Forgery).

React Js HTTP Asynchronous GET Request with React Hooks Tutorial

  • Step 1: Create React App
  • Step 2: Add Axios in React
  • Step 3: Create Component
  • Step 4: Make Axios Asynchronous HTTP GET Request
  • Step 5: Update App Js
  • Step 8: Run Application

Create React App

We will start by creating brand new React application, you can do it by using the given command.

npx create-react-app react-test

Let’s use the cd command to get inside your project folder.

cd react-test

Add Axios in React

Once again, type the given command on the command prompt and install the Axios library in your React app.

npm install axios

Create Component

We will show you the asynchronous Get request demo in React functional component.

Here is the code that you have to add it into the components/AsyncGetReq.js file, it will create a stateless React component.

import React from 'react'

export default function AsyncGetReq() {
  return (
    <div>
      
    </div>
  )
}

Make Axios Asynchronous HTTP GET Request

First, you have to import the Axios package.

Set the state with the help of the useState hook; the first value is the users variable; another value is the function that returns the users data.

Use the async attribute with the getReq function; in the try block, use the axios.get method, and the first parameter will be API.

The second parameter sets the headers; then, you can set the state through the initUser() value.

We are using the useEffect hook to handle the Axios Get request; this hook deals with componentDidMount, componentDidUpdate, and componentWillUnmount altogether, similarly like react class component.

Add code in components/AsyncGetReq.js.

import React, { useState, useEffect } from 'react'
import axios from 'axios'

export default function AsyncGetReq() {
  const [users, initUser] = useState([])

  const getReg = async () => {
    try {
      const res = await axios.get(
        'https://jsonplaceholder.typicode.com/users',
        {
          headers: {
            authorization: 'Bearer JWT_Token_Goes_Here',
          },
        },
      )

      initUser(res.data)
    } catch (e) {
      console.log(e)
    }
  }

  useEffect(() => {
    window.addEventListener('load', getReg)
    return () => {
      window.removeEventListener('load', getReg)
    }
  }, [users])

  return (
    <div>
      {users.map((item) => {
        return <li key={item.id}>{item.name}</li>
      })}
    </div>
  )
}

Update App Js

Once the component is ready, make sure to register the component into the main component.

Hence add code in the App.js file, as given below.

import React from 'react'

import AsyncGetReq from './components/AsyncGetReq'

export default function App() {
  return (
    <div>
      <AsyncGetReq />
    </div>
  )
}

Run Application

Now we are ready to show you the authorization header, asynchronous response and the data list that we retrieved using the http Get request in React.

Ensure that you run the following command from the terminal.

npm start

Make Asynchronous HTTP Get Request in React with Axios

Summary

Throughout this chapter, we understood how to make asynchronous HTTP requests with Axios in React. So far, we have learned how to create asynchronous get request with useState and useEffect hooks.

We also showed how to use asynchronous HTTP request in React functional components with React hooks.