API Calls With React and Axios

Axios is used to fetch data from API call.

You can get dummy API URLs from https://www.randomuser.me/

Install axios npm package in your project

npm install axios --save

Note: –save will add axios in your package.json

After the successful installation of the package, Let’s add axios in your component.

import axios from 'axios'

Create a state object in the constructor so we can use its updated value in our component.

 constructor(props){
  super(props);
  this.state={
   data:[],
  };
}

Create your axios request in componentDidMount function or any other function that you want to execute.

var api_url="https://randomuser.me/api";//set your endpoints here

var method="GET", //type of your request(POST,GET,PUT,DELETE...)

//request header
var headers={
"Content-Type":"application/json"
}

axios.request({
   url: api_url,
   method: method,
   headers: headers,
  })
.then((res)=>{
       this.setState({
         data:res
     });
})
.catch((error)=>{
//on error
});

Once we successfully fetched data from API, we need to render data in our HTML as per requirement. To render an object we mostly use the map function.

{this.state.data.map(function(item, index){
return (
<div className="info">

<p><span>{item.name}</span>:<span>{item.gender}</span></p>

</div>
)
})}

Leave a Reply

Your email address will not be published. Required fields are marked *