How to use axios with Reactjs
Blog React How to use axios with Reactjs

Axios is a Promise based http client for the browser as well as for the Node. Axios is light weight, simple to use npm pacakge for your daily REST APIs needs. At end of this post you will gonna learn how to use axios with the Reactjs.

Features

Axios have a lot of features some of them are given below:-

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

Installation

Installation of Axios is very simple. To install axios using npm you can use
npm install axios --save

If you want to use it using cdn you can do that using below script

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

How to use axios with Reactjs

Axios is a promised-based package that mean we can use it async-await.

you can import it using following ways:-

using es5/common js

const axios = require('axios');

using es6

import axios from 'axios';

Get Request using Axios

We will going to add axios.get method in the componentDidMount lifecycle method and gonna do a get request to the 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 (
      <ul>
        { this.state.users.map(person => <li>{person.name}</li>)}
      </ul>
    )
  }
}

Post/Put Request using Axios

We can do the post/put request with almost similar syntax of get. In below example we will gonna do a post request 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>
    )
  }
}

Delete Request using axios

Delete request is also similar to rest of the request. In the below example we are going to delete a user using its 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>
    )
  }
}

How to use async and await with axios

We can also use async and await with axios to make our code more cleaner. To use async and await with axios you need to add async keyword next to your function. After that you just need to add await keyword next to your api call and don’t forget to wrap your code with try catch to catch all the error.

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

  const response = await API.delete(`https://jsonplaceholder.typicode.com/users/${this.state.id}`);

  console.log(response);
  console.log(response.data);
}
catch(error){
   console.log("Error",error);
}
};

If you want to learn about error boundaries in the reactjs you can learn here.

Categories: Reactjs

1 Comment

How to create single instance of Axios in React - Blog React · February 6, 2020 at 3:35 am

[…] Axios is a Promise based http client for the browser as well as for the Node. Axios is light weight, simple to use npm pacakge for your daily REST APIs needs. If you want to learn how to use axios you can checkout here. […]

Comments are closed.