Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Make HTTP Requests with Axios or Fetch in a React Web Application

TwitterFacebookRedditLinkedInHacker News

In most client facing applications there’s a need to consume data from remote web services, also referred to as APIs. This is because there is a separation of backend and frontend logic in modern applications, not specific to the web. With JavaScript, there are quite a few options when it comes to making HTTP requests, some of which I explored in my previous tutorial titled, Execute HTTP Requests in JavaScript Applications.

What if we wanted to execute HTTP requests using a popular framework like React?

In this tutorial, we’re going to look at what it takes to make HTTP requests and consume data from remote web services using React and simple JavaScript.

To get an idea of what we want to accomplish, take a look at the following image:

React HTTP Example

In the above example we are making an HTTP request and using the response to render information on the screen. The response information being the name and website information.

Creating a Simple React Web Application

To keep things simple, we’re going to start with a fresh project and boilerplate React code. From the command line, execute the following:

npx create-react-app example-project

For this particular project, we’re going to do all of our work in the src/App.js file. Open the src/App.js file and include the following boilerplate code:

import React from "react";
import logo from './logo.svg';
import './App.css';

class App extends React.Component {

    constructor() {
        super()
        this.state = {
            firstname: "Foo",
            lastname: "Bar",
            website: ""
        }
    }

    render() {
        return (
            <div className="App">
                <header className="App-header">
                    <img src={logo} className="App-logo" alt="logo" />
                    <p>{this.state.firstname} {this.state.lastname}</p>
                    <p>{this.state.website}</p>
                </header>
            </div>
        );
    }

}

export default App;

The above code is not what we’d find in a vanilla project. We’ve actually added a constructor method with state variables and applied those state variables within the render function. It’s not great practice to work with state variables in the App class, but we’re going to let it slide for this example.

Consume Data with a JavaScript Fetch in a React Application

Because options are a good thing, we’re going to look at a few examples, the first of which will use the fetch function, which is found in modern JavaScript implementations.

Within the src/App.js file, include the following function:

makeGetRequest() {
    return fetch("http://httpbin.org/get?firstname=Nic&lastname=Raboy")
        .then(response => response.json())
        .then(response => response.args);  
}

Because we don’t want to configure our own RESTful API for this example, we’re using an HTTP mocking service. The idea is that we are using the fetch command to send a GET request with query parameters. The response will contain the data that we sent.

Having the makeGetRequest function won’t actually execute the function. Instead, we are going to make use of the componentDidMount life-cycle event in React.

async componentDidMount() {
    try {
        let getResult = await this.makeGetRequest(); 
        this.setState({
            "firstname": getResult.firstname, 
            "lastname": getResult.lastname
        });
    } catch (e) {
        console.error(e);
    }      
}

When the componentDidMount function triggers, an HTTP request will be made using the makeGetRequest function that we created. The firstname and lastname from the result will be added to the state which will automatically render to the screen.

Leverage Third-Party Libraries Like Axios for HTTP Requests in React

While the fetch function in JavaScript can handle pretty much anything anyone would need from a RESTful API, it might not always be the most simple or most elegant. Instead we can make use of a third-party library to get the job done.

For this example we’re going use axios for making requests.

From the command line, execute the following:

npm install axios --save

With axios installed, we can make use of it within our application. Open the project’s src/App.js file and include the following import:

import axios from "axios";

Now that axios has been imported into the project, we can make a function, similar to how we did it with the fetch command. Create a makePostRequest function that looks like the following:

makePostRequest() {
    return axios({
        "method": "POST",
        "url": "http://httpbin.org/post",
        "data": {
            "website": "www.thepolyglotdeveloper.com"
        }
    }).then(response => response.data.json);
}

Like with the fetch example, we’re going to use an HTTP mock service to save us from having to design our own API. This time around we’re making a POST request and sending a payload that we expect back as a response.

If we make changes to our componentDidMount method, we can do this:

async componentDidMount() {
    try {
        let postResult = await this.makePostRequest();
        let getResult = await this.makeGetRequest(); 
        this.setState({
            "firstname": getResult.firstname, 
            "lastname": getResult.lastname,
            "website": postResult.website
        });
    } catch (e) {
        console.error(e);
    }      
}

We didn’t undo any of the fetch functionality that we had previously added. However, now we’ve executed our makePostRequest function and are using the results when we set the state variables. The result of the makePostRequest is the website that we sent.

In both HTTP examples, we make use of the mock API service. The response of this service is just the data that we send it. We’re doing this so we don’t need to make our own API for this example, but we can still work with an API and handle the response.

Conclusion

You just saw how to make HTTP requests in a React application using both Fetch and Axios. These are two options of many possible options when it comes to making HTTP requests to send or consume data from remote web services and APIs.

If you want to learn more about making HTTP requests in JavaScript, check out my previous tutorial which has more in depth examples.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

Search

Follow Us

The Polyglot Developer

Subscribe

Subscribe to the newsletter for monthly tips and tricks on subjects such as mobile, web, and game development.

The Polyglot Developer

Support This Site