How to use Axios with ReactJS Application

    Aug 25, 2018       by Pankaj Kumar
how-to-use-axios-with-reactjs-app.jpg

In this article, I am going to explain how to use Axios for GET, POST, PUT and other HTTP requests in React.js application. I will use MongoDB, Node, and Express.js to create a backend server for the React app.

I assume that you have already available the above tools/frameworks and you are familiar with all the above that what individually actually does.

As we know that we can easily start working on React.js with the create-react-app tool. Here I will skip this because you would be familiar with the basic stuff of React.js. If you are not aware of creating the React.js app with the above tool. React my article on it Getting Started with React.js

 

What is Axios?

Axios is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node.js. We can use Axios with React to make requests to an API, return data from the API, and then do things with that data in our React app.

With Axios, A developer can also take advantage of async/await for more readable asynchronous code.

 

Here we will use JSON placeholder API for fetching the list of dummy users. 

 

Install Axios

At first, we need to install Axios into the react project. Run below command to install it in the project.

// install with yarn

yarn add axios

// install with npm

npm install axios --save

 

GET Request with Axios

Create a new component named UserList and hook it into the componentDidMount lifecycle and fetch data with Get request after importing axios

 

 
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 (
      <ul>
        { this.state.users.map(user => <li>{user.name}</li>)}
      </ul>
    )
  }
}
 

 

In the above code, At the top React & Axios library is imported. axios.get(URL) is used to get a promise which returns a response object. The received data in res.data is assigned to users. Information like status code and others can also be received with the response.

 

POST Request with Axios

As we know that Axios also handle another HTTP request such as POST, PUT, etc. So create another component named AddUser for showing an example of POST request which will add a user and put below code inside it.

 

 
import React from 'react';
import axios from 'axios';
 
export default class AddUser 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>
        Person Name:
        <input type="text" name="name" onChange={this.handleChange} />
        </label>
        <button type="submit">Add</button>
        </form>
      </div>
    )
  }
}
 

 

The above code mainly makes an HTTP POST request to the server and add the data to the database.

 

DELETE Request with Axios

axios.delete is used to make Delete request to the server, URL need to pass into it as a parameter.

 

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

 

 

Conclusion

So in this article, We learn how to use Axios in React.js application with the different request methods available with it. You can also find other demos of React.js Sample Projects here to start working on enterprise-level applications.

 

That’s all for now. Thank you for reading and I hope this demo will be very helpful for how to use Axios in React.js application.

Let me know your thoughts over email demo.jsonworld@gmail.com. I would love to hear them and If you like this article, share it with your friends.

You can download complete code from here. Download Code


WHAT'S NEW

Find other similar Articles here: