API Integration with Axios in React

In this blog, we will learn how to consume web service in our react application.We are going to use axios as HTTP client for making HTTP Requests, so before dive in let’s understand little bit about axios, it’s features and how we can make http requests using axios.

Axios

Axios is a promise based HTTP client for making http request from browser to any web server.

Features of Axios

  • For making XMLHttpRequests from browser to web server
  • Make http request from node js
  • Supports the promise API
  • Handle request and response
  • Cancel requests
  • Automatically transform JSON data

 

Installation

Using npm

$ npm install axios -- save

Example of get and post request

//post request

axios.post(‘/url’,{data:’data’}).then((res)=>{
	//on success
}).catch((error)=>{
	//on error
});

//get request

axios.get(‘/url’,{data:’data’}).then((res)=>{
	//on success
}).catch((error)=>{
	//on error
});

Performing multiple concurrent requests

function getUserAccount() {
  return axios.get('/user/12345');
}
 
function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}
 
axios.all([getUserAccount(), getUserPermissions()])
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));

Using axios in our react application

I am assuming that you have basic knowledge of react fundamentals and it’s life cycle methods.

Steps to use axios in our react application –

Step 1 : In order to make a HTTP request, we need to install axios and add it’s dependency in our package.json file. If you have not already installed then use this command in your terminal.

npm install axios --save

Step 2 : In order to use axios in our project we need to import axios from our node modules.

import axios from "axios";

Step 3 : Now create a React component, where we want to consume any web service in our react application.

Here, we want to display user message suppose, so we make a component and initialize with initial state.

import React,{Component} from  ‘react’;

class UserMsg extends Component{
	constructor(){
	super();
	this.state={
		userMsg:null
	}
}
render(){
	return(
			{
				this.state.userMsg!=null &&
				<div>
	<h2>{this.state.userMsg.title}</h2>
	<p>{this.state.userMsg.body}</p>
</div>
			}			
		);
	}
}  

export default UserMsg;

 

Step 4 : Now make rest call inside componentDidMount method of react component lifecycle.

componentDidMount is executed after first render only on the client side. This is where AJAX requests and DOM or state updates should occur. This method is also used for integration with other JavaScript frameworks and any functions with delayed execution like setTimeout or setInterval. We are using it to update the state so we can trigger the other lifecycle methods.

We are making get request with a public api ‘https://jsonplaceholder.typicode.com/posts/1

That will return json

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto"
}

In componentDidMount method we make rest api call and set the state to display on UI.

componentDidMount(){
	axios.get(‘https://jsonplaceholder.typicode.com/posts/1’,{}).then((res)=>{
		//on success
		this.setState({
	userMsg:res.data
});
		
}).catch((error)=>{
	//on error
	alert(“There is an error in API call.”);
});
}

Here is output of complete program.

import React,{Component} from "react";
import axios from "axios";

class UserMsg extends Component{
	constructor(){
		super();
		this.state={
			userMsg:null
		}
	}
	componentDidMount(){
		axios.get("https://jsonplaceholder.typicode.com/posts/1",{}).then((res)=>{
				//on success
				this.setState({
			userMsg:res.data
		});
				
		}).catch((error)=>{
			//on error
			alert("There is an error in API call.");
		});
	}

render(){
	return(
			
				this.state.userMsg!=null &&
				<div>
					<h2>{this.state.userMsg.title}</h2>
					<p>{this.state.userMsg.body}</p>
				</div>
						
		);
	}
}  

export default UserMsg;

Output

 

Leave a Reply