React Tutorials

React Axios Send Asynchronous HTTP GET Request Tutorial

For experienced developers getting data or fetching records from the server is no big deal. But if you are new to React and utterly unaware of obtaining records from the server.

In this detailed tutorial, you will learn how to send HTTP Get request using the Axios library in React.

Let us understand what HTTP get request is?

HTTP GET requests are sent using the Get method. The primary job of the HTTP Get method is to retrieve data from a server using a specific URL.

GET requests are only used to get data in any case; it does not modify or update the data state on the server.

Therefore, the GET HTTP method is recognized as the most notable HTTP method. In this React HTTP Get method example, we combine Axios in React and harness the true powers of both.

How to Make HTTP GET Request in React using Axios

  • Step 1: Install React Project
  • Step 2: Create REST Server
  • Step 3: Install Axios Plugin
  • Step 4: Fetch Data with HTTP Get Method
  • Step 5: Add Component in App File
  • Step 6: Run React Server

Install React Project

As far as we know, you must have created the React application, in case if you don’t.

Then get along…

Open the terminal on your system, jump onto the console. To install the React blank project, we will use the create-react-app tool.

As far as the project name is concerned, you may git any name.

npx create-react-app react-blog

Next, enter into the app through following command.

cd react-blog

Create REST Server

Our main goal is to show you how to make GET request in React. For that, we need an API. An API is a URL that points towards the server.

It might be remotely located, but you can also create it locally for testing purposes.

In this step, we will create the REST server, which will give us the API or endpoint. With the help of that API, we can receive the data in React component.

Let us install the json-server library.

npm install json-server

Within your app folder, create a new db.json file and create the profiles object and pour some data into the object in json form.

{
  "profiles": [
    {
      "id": 1,
      "name": "Leanne Graham",
      "username": "Bret",
      "email": "Sincere@april.biz",
      "address": {
        "street": "Kulas Light",
        "suite": "Apt. 556",
        "city": "Gwenborough",
        "zipcode": "92998-3874",
        "geo": {
          "lat": "-37.3159",
          "lng": "81.1496"
        }
      },
      "phone": "1-770-736-8031 x56442",
      "website": "hildegard.org",
      "company": {
        "name": "Romaguera-Crona",
        "catchPhrase": "Multi-layered client-server neural-net",
        "bs": "harness real-time e-markets"
      }
    },
    {
      "id": 2,
      "name": "Ervin Howell",
      "username": "Antonette",
      "email": "Shanna@melissa.tv",
      "address": {
        "street": "Victor Plains",
        "suite": "Suite 879",
        "city": "Wisokyburgh",
        "zipcode": "90566-7771",
        "geo": {
          "lat": "-43.9509",
          "lng": "-34.4618"
        }
      },
      "phone": "010-692-6593 x09125",
      "website": "anastasia.net",
      "company": {
        "name": "Deckow-Crist",
        "catchPhrase": "Proactive didactic contingency",
        "bs": "synergize scalable supply-chains"
      }
    },
    {
      "id": 3,
      "name": "Clementine Bauch",
      "username": "Samantha",
      "email": "Nathan@yesenia.net",
      "address": {
        "street": "Douglas Extension",
        "suite": "Suite 847",
        "city": "McKenziehaven",
        "zipcode": "59590-4157",
        "geo": {
          "lat": "-68.6102",
          "lng": "-47.0653"
        }
      },
      "phone": "1-463-123-4447",
      "website": "ramiro.info",
      "company": {
        "name": "Romaguera-Jacobson",
        "catchPhrase": "Face to face bifurcated interface",
        "bs": "e-enable strategic applications"
      }
    },
    {
      "id": 4,
      "name": "Patricia Lebsack",
      "username": "Karianne",
      "email": "Julianne.OConner@kory.org",
      "address": {
        "street": "Hoeger Mall",
        "suite": "Apt. 692",
        "city": "South Elvis",
        "zipcode": "53919-4257",
        "geo": {
          "lat": "29.4572",
          "lng": "-164.2990"
        }
      },
      "phone": "493-170-9623 x156",
      "website": "kale.biz",
      "company": {
        "name": "Robel-Corkery",
        "catchPhrase": "Multi-tiered zero tolerance productivity",
        "bs": "transition cutting-edge web services"
      }
    },
    {
      "id": 5,
      "name": "Chelsey Dietrich",
      "username": "Kamren",
      "email": "Lucio_Hettinger@annie.ca",
      "address": {
        "street": "Skiles Walks",
        "suite": "Suite 351",
        "city": "Roscoeview",
        "zipcode": "33263",
        "geo": {
          "lat": "-31.8129",
          "lng": "62.5342"
        }
      },
      "phone": "(254)954-1289",
      "website": "demarco.info",
      "company": {
        "name": "Keebler LLC",
        "catchPhrase": "User-centric fault-tolerant solution",
        "bs": "revolutionize end-to-end systems"
      }
    },
    {
      "id": 6,
      "name": "Mrs. Dennis Schulist",
      "username": "Leopoldo_Corkery",
      "email": "Karley_Dach@jasper.info",
      "address": {
        "street": "Norberto Crossing",
        "suite": "Apt. 950",
        "city": "South Christy",
        "zipcode": "23505-1337",
        "geo": {
          "lat": "-71.4197",
          "lng": "71.7478"
        }
      },
      "phone": "1-477-935-8478 x6430",
      "website": "ola.org",
      "company": {
        "name": "Considine-Lockman",
        "catchPhrase": "Synchronised bottom-line interface",
        "bs": "e-enable innovative applications"
      }
    },
    {
      "id": 7,
      "name": "Kurtis Weissnat",
      "username": "Elwyn.Skiles",
      "email": "Telly.Hoeger@billy.biz",
      "address": {
        "street": "Rex Trail",
        "suite": "Suite 280",
        "city": "Howemouth",
        "zipcode": "58804-1099",
        "geo": {
          "lat": "24.8918",
          "lng": "21.8984"
        }
      },
      "phone": "210.067.6132",
      "website": "elvis.io",
      "company": {
        "name": "Johns Group",
        "catchPhrase": "Configurable multimedia task-force",
        "bs": "generate enterprise e-tailers"
      }
    },
    {
      "id": 8,
      "name": "Nicholas Runolfsdottir V",
      "username": "Maxime_Nienow",
      "email": "Sherwood@rosamond.me",
      "address": {
        "street": "Ellsworth Summit",
        "suite": "Suite 729",
        "city": "Aliyaview",
        "zipcode": "45169",
        "geo": {
          "lat": "-14.3990",
          "lng": "-120.7677"
        }
      },
      "phone": "586.493.6943 x140",
      "website": "jacynthe.com",
      "company": {
        "name": "Abernathy Group",
        "catchPhrase": "Implemented secondary concept",
        "bs": "e-enable extensible e-tailers"
      }
    },
    {
      "id": 9,
      "name": "Glenna Reichert",
      "username": "Delphine",
      "email": "Chaim_McDermott@dana.io",
      "address": {
        "street": "Dayna Park",
        "suite": "Suite 449",
        "city": "Bartholomebury",
        "zipcode": "76495-3109",
        "geo": {
          "lat": "24.6463",
          "lng": "-168.8889"
        }
      },
      "phone": "(775)976-6794 x41206",
      "website": "conrad.com",
      "company": {
        "name": "Yost and Sons",
        "catchPhrase": "Switchable contextually-based project",
        "bs": "aggregate real-time technologies"
      }
    },
    {
      "id": 10,
      "name": "Clementina DuBuque",
      "username": "Moriah.Stanton",
      "email": "Rey.Padberg@karina.biz",
      "address": {
        "street": "Kattie Turnpike",
        "suite": "Suite 198",
        "city": "Lebsackbury",
        "zipcode": "31428-2261",
        "geo": {
          "lat": "-38.2386",
          "lng": "57.2232"
        }
      },
      "phone": "024-648-3804",
      "website": "ambrose.net",
      "company": {
        "name": "Hoeger LLC",
        "catchPhrase": "Centralized empowering task-force",
        "bs": "target end-to-end models"
      }
    }
  ]
}

Now, we will start the REST server, –watch tag reload the server when detect the change in the data object.

On the other hand –port starts the server on the defined port.

json-server --watch db.json --port=5555

After running the command given url appear on your console. Copy it, we will need it shortly.

http://localhost:5555/users

Install Axios Plugin

Now, head over to terminal and again type a new command this command will help you install the axios client in React app.

npm install axios

Fetch Data with HTTP Get Method

We will receive the data in the component, so create the components/ directory.

Also, create a Profile.js file in components directory. And after that copy the given code and paste it in the file.

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

export default function Profile() {
  const API_URI = 'http://localhost:9999/profiles'

  const [profile, setProfile] = useState([])

  const getProfiles = async () => {
    try {
      const fetchData = await axios.get(API_URI, {
        headers: {
          authorization: 'Bearer JWT Token',
        },
      })
      setProfile(fetchData.data)
    } catch (error) {
      console.log(error)
    }
  }

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

  return (
    <div className="container mt-4">
      <h2 className="mb-4">React Axios HTTP GET Request Example</h2>
      {profile.map((res) => {
        return (
          <li
            className="card p-3 mb-2 bg-secondary bg-gradient text-white"
            key={res.id}
          >
            <div className="card-body">
              <h5 className="card-title">{res.username}</h5>
              <p className="card-text">{res.email}</p>
            </div>
          </li>
        )
      })}
    </div>
  )
}

Add Component in App File

In this step, we will have to again open the App.js file and import and register the profile component.

import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'
import Profile from './components/Profile.js'

function App() {
  return (
    <div>
      <Profile />
    </div>
  )
}

export default App;

Run React Server

Type the command on the console and press enter to run the React server.

npm start

Open your app on given url:

http://localhost:3000

Thats what you see when you will open the app:

Conclusion

In this lesson, we revealed how a beginner developer could start his React development journey. We learned how to create a React app, create a demo REST server in React.

How to retrieve data from server using HTTP GET request. We believe you must have developed the understanding of using the Http Get method in React.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.

Recent Posts

React Redux Handle API Calls with Thunk Middleware Tutorial

In this post, we will learn how to work with HTTP requests in the Redux…

1 day ago

Node AJAX Retrieve Records from MySQL Database Tutorial

MySQL is a relational database management system based on SQL – Structured Query Language, and…

4 days ago

React Manage REST API State Globally with Context API Tutorial

React Js Handle Rest API data globally with Context and useState hook tutorial. In this…

1 week ago

How to Delete Data from MySQL Database using Node Js

Node js delete data from MySQL database tutorial; Throughout this guide, you will ascertain how…

1 week ago

Node Import CSV File Data to MySQL Database with HTML Form

In this tutorial, you will discover how to import CSV file into MySQL database using…

2 weeks ago

How to Handle Global State in React js using Context API

React Js Global state management with createContext hook example; In this tutorial, we will help…

2 weeks ago