Member-only story
REST API Consumption in React With Fetch, Axios, and Axios Hooks
When to use Fetch and Axios in your applications?
There are various ways of consuming REST APIs in React but in this blog, we will be focussing on how we can consume REST APIs using two of the most popular methods:
- Axios (a promise-based HTTP client)
- Fetch API (a browser in-built web API).
We also discuss the hooks version of Axios using axios-hooks
.
First, let’s create a sample react application to demonstrate Rest API consumption in React App.
The application is capable of calling an endpoint that gives random user info. For now, we only print the full name and email of the user.
import React,{useEffect,useState} from "react";
const RenderUserInfo = (props) => {
const { name, email } = props;
return (
<div>
<p>Name: {name}</p>
<p>Email: {email}</p>
</div>
);
};
const UserList = () => {
const [userList,setUserList] = useState([])
const apiCall=()=>{
// API logic goes here
}
useEffect(()=>{
apiCall()
},[])
return (<div>
{userList.map((item, index) => (
<RenderUserInfo name={item.name} email={item.email} key={index} />…