Integrating Axios in React.js project

Axios is a lightweight HTTP client based on the $https service within Angular.js v1.x. It is similar to native JavaScript Fetch API. Axios’s working is promise based. You can make use of the JavaScript async and await with more readable code. To use Axios you need Node.js version 10.16.0 on your system. A new React project folder. To add Axios to your React project navigate to your react application. 

cd new react project

Then run the below command.

npm install axios

The project folder will be empty at first so create a directory and name it utils. Then create a new file API.js and store the below given configuration in it.

// utils/API.js
import axios from "axios";

export default axios.create({
  baseURL: "https://randomuser.me/api/",
  responseType: "json"
});

API.js file has code to import Axios and it exports its new configured instance also. It's set up so that the RandomUser API can be used as a base URL and get JSON in return.  

Lets see an example for GET requests using Axios. Here the axios.get method is added to componentDidMount lifecycle method and does a get request to jsonplaceholder api.

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

export default class UserList extends React.Component {
  state = {
    persons: []
  }

  componentDidMount() {
    axios.get(`https://jsonplaceholder.typicode.com/users`)
      .then(res => {
        const users = res.data;
        this.setState({ users });
      })
  }
  render() {
    return (
      
    { this.state.users.map(person =>
  • {person.name}
  • )}
) } }

Post/Put request example. Here a post request is done using some dummy data from form.


import React from 'react';

import axios from 'axios';


export default class PostRequest extends React.Component {

  state = {

    name: '',

  }

  handleChange = event => {

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

  }

  handleSubmit = event => {

    event.preventDefault();

    const user = {

      name: this.state.name

    };

    axios.post(`https://jsonplaceholder.typicode.com/users`, { user })

      .then(res => {

        console.log(res);

        console.log(res.data);

      })

  }

  render() {

    return (

      <div>

        <form onSubmit={this.handleSubmit}>

          <label>

            User Name:

            <input type="text" name="name" onChange={this.handleChange} />

          </label>

          <button type="submit">Add</button>

        </form>

      </div>

    )

  }

}


Now we will see an example for delete requests using axios. In this example we are deleting a user using the name from jsonplaceholder api.


import React from 'react';

import axios from 'axios';


export default class DeleteRequest extends React.Component {

  state = {

    id: '',

  }

  handleChange = event => {

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

  }

  handleSubmit = event => {

    event.preventDefault();

    axios.delete(`https://jsonplaceholder.typicode.com/users/${this.state.id}`)

      .then(res => {

        console.log(res);

        console.log(res.data);

      })

  }

  render() {

    return (

      <div>

        <form onSubmit={this.handleSubmit}>

          <label>

            Person ID:

            <input type="text" name="id" onChange={this.handleChange} />

          </label>

          <button type="submit">Delete</button>

        </form>

      </div>

    )

  }

}