Tutorials > How to make HTTP Requests with Axios and React.js

How to make HTTP Requests with Axios and React.js

Published on: 01 July 2021

Development React.js

Introduction

Axios is a Javascript library that allows you to connect with the backend API and manage requests made via the HTTP protocol.

The advantage of Axios lies in its being promise-based, thus allowing the implementation of asynchronous code. The asynchronous code will allow, on a page, to load multiple elements simultaneously instead of sequentially, significantly reducing loading times.

The Promise, which Axios is based on, is instead a Javascript object that allows you to complete requests asynchronously, passing through three states (pending, satisfied, rejected).

This guide will show some examples of how to make asynchronous HTTP GET and POST requests in a React.js application using the Axios library.

Prerequisites

To follow the examples some steps have to be completed:

  • Have Node.js installed in version 10.16.0
  • Having created a new project with React
  • Have a basic knowledge of Javascript.

If you're ready, let's start with the first step of the tutorial.

Adding Axios to your project

The first part is to install Axios into your project with React.

This step is very simple, as you just need to move to the project directory and then launch the Axios installation command.

$ cd mysampleproject
$ npm install axios

Import Axios and implement a GET request

Now, simply integrate the Axios import into a code file.

Start by creating a .js file :

$nano src/invitationList.js

Inside it, add these lines of code:

import React from 'react';

import axios from 'axios';

export default class PostList extends React.Component {
 state = {
  posts: []
 }

 componentDidMount() {
  axios.get(`https://jsonplaceholder.typicode.com/posts`)
 .then(res => {
    const posts = res.data;
    this.setState({ posts });
   })
 }

 render() {
  return (
   <ul>
    { this.state.posts.map(post => <li>{post.title}</li>)}
   </ul>
  )
 }
}

Within this code, the first part of the instructions is for importing React and Axios to make them usable in the component.

The part where the request is performed is instead that of componentDidMount. Here, through the command axios.get (url), execute a GET request to an API to have a promise that should return an object containing the data to be assigned to post.

Implementing a POST request

In this other example, the previous file can be built with a different source code, to request input from the user and send its content, via the POST method, to an API.

import React from 'react';
import axios from 'axios';

export default class PostList extends React.Component {
 state = {
  title: '',
 }

 handleChange = event => {
  this.setState({ name: event.target.value });
 }

 handleSubmit = event => {
  event.preventDefault();

  const post = {
   title: this.state.title
  };

  axios.post(`https://jsonplaceholder.typicode.com/posts`, { post })
 .then(res => {
    console.log(res);
    console.log(res.data);
   })
 }

 render() {
  return (
   <div>
    <form onSubmit={this.handleSubmit}>
     <label>
      Post Title:
      <input type="text" name="title" onChange={this.handleChange} />
     </label>
     <button type="submit">Add</button>
    </form>
   </div> 
  )
 }
}

Inside the handleSubmit function, set the default action of the form and update the status with the title of the message.

Via the POST method, you will be returned the same response object with usable information in a then call.

Collecting the post input, the code adds it to the POST request, which will give a response. The response will be visible via the console.log.

Implementing a DELETE request

To delete an object from an API, use the axios.delete method, passing the URL of the object to be deleted as the request parameter.

In the example, the same code is implemented for the form with the POST method but here information from a previously created message can be deleted.

import React from 'react';
import axios from 'axios';

export default class PostList extends React.Component {
 state = {
  id: '',
 }

 handleChange = event => {
  this.setState({ id: event.target.value });
 }

 handleSubmit = event => {
  event.preventDefault();


   axios.delete(`https://jsonplaceholder.typicode.com/posts/${this.state.id}`)
 .then(res => {
    console.log(res);
    console.log(res.data);
   })
 }

 render() {
  return (
   <div>
    <form onSubmit={this.handleSubmit}>
     <label>
      Post ID:
      <input type="text" name="id" onChange={this.handleChange} />
     </label>
     <button type="submit">Delete</button>
    </form>
   </div> 
  )
 }
}

Using a Base instance in Axios

In this example, you will be shown how to use a base instance, which is useful for defining a URL and various Axios configuration items.

First of all, create a new file called api.js :

$ nano src/api.js

Now, create a default configuration inside the file and export it:

import axios from 'axios';

export default axios.create({
 baseURL: `http://jsonplaceholder.typicode.com/`
});

Once this is done, just import the file to be able to include the configuration in your code:

import React from 'react';
import axios from 'axios';

import API from '../api';

export default class PostList extends React.Component {
 handleSubmit = event => {
  event.preventDefault();

  API.delete(`posts/${this.state.id}`)
 .then(res => {
    console.log(res);
    console.log(res.data);
   })
 }
}

Thanks to this example, the default URL to be called in the code in order to save time in entirely rewriting it will have been imported, by pointing to a different section of the API.

Using async and await to work with promises

In the following example, these two methods will be applied to handle a request as a promise (asynchronous request):

handleSubmit = async event => {
 event.preventDefault();

 //
 const response = await API.delete(`posts/${this.state.id}`);

 console.log(response);
 console.log(response.data);
};

As shown, the await method fulfills the promise by deleting the user from the API and returning a value in the response variable.

The .then () method  has been dropped and the request has been delegated to the method just shown.

Conclusions

Thanks to this tutorial and the examples shown, you have been able to discover the advantages of Axios and have learned how to use them within your React applications to create and manage requests in HTTPS.