How to use Axios with React

Ishwar Deoolkar
Nerd For Tech
Published in
4 min readApr 18, 2021

--

Here is my experience of how to use Axios with react (everything you need to know)

Axios for API Call in React

Working on react from last 3 years. It’s a tremendous journey and provides many confidence to unravel world problems. And main thought process to write down this text for developer who started learning react (beginner level or intermediate level) to assist them how they will use API call in react using Axios.

Before diving into Axios, You need to have basic knowledge of javascript and XMLHttpRequest. XMLHttpRequest object can be used to request data from a web server. The XMLHttpRequest object is a developers dream because you can:

  • Update a web page without reloading the page
  • Request data from a server — after the page has loaded
  • Send data to a server — in the background
  • Receive data from a server — after the page has loaded

To know more about XMLHttpRequest.

In this article, I am going to explain how to use Axios for GET, POST, PUT, and other HTTP requests in React application

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.

Install Axios

At first, we need to install Axios into the react project. Use the below commands to install.

// Install with npm
npm install axios
or// Install with yarn
yarn add axios
or// Install with bower
bower install axios

Once you installed the Axios in your package.json. Let’s start writing some code snippets. To call Axios we need to know to follow things -

  1. Requested URL.
  2. Method — (GET, POST, or PUT, etc.,)
  3. headers

Here how your folder structure should look like for Axios call in your application -

src/components-
-- Datalayer
-- axiosMethodCalls.js
-- datalayerUtilities.js
-- Configuration
-- config_url.js

Keep all your endpoint in a specific file — In this scenario config_url.js. So where we can have a track of all endpoints in one file in your application.
For example — config_url.js

// All Endpoints.
export const jokeCategoriesUrl = `https://api.chucknorris.io/jokes/categories`;
export const mockablePostUrl = `http://demo0725191.mockable.io/post_data`;export const mockablePutUrl = `http://demo0725191.mockable.io/put_data`;export const mockableDeleteUrl = `http://demo0725191.mockable.io/delete_data`;

Keep your all Axios method call in specific file — In this scenario axiosMethodCalls.js where we can have a track of all Axios method call in one file in your application.
For example — axiosMethodCalls.js
I have created some generic functions for Axios method calls such as GET, POST, PUT, and DELETE.

// API Axios Get Call.
export const getAPICall = (url) => {
return axios.get(url);
}
// API Axios Post Call.
export const postAPICall = (url, data) => {
return axios.post(url, data);
}
// API Axios Put Call.
export const putAPICall = (url, data) => {
return axios.put(url, data);
}
// API Axios Delete Call.
export const deleteAPICall = (url) => {
return axios.delete(url);
}

Keep your all Axios call in specific file — In this scenario datalayerUtilities.js where we can have a track of all API call in one file in your application.
For example — datalayerUtilities.js

// Import the endpoints.
import { jokeCategoriesUrl, mockablePostUrl, mockablePutUrl, mockableDeleteUrl } from './configuration/config_url';
// Import the axios Method.
import { getAPICall, postAPICall, putAPICall, deleteAPICall } from './axiosMethodCalls';

GET Requests -

// Axios Get Call - Get all jokes categories.
export const getJokeCategorieData = async () => {
try {
const response = await getAPICall(jokeCategoriesUrl);
return response.data;
}
catch(error){
return error.response;
}
}

POST Requests -

// Axios Post Call - MockablePost.
export const mockablePostData = () =>{
try {
const response = await postAPICall('mockablePostUrl', {
posted_data: 'example' });
console.log('👉 Returned data:', response);
}
catch (error) {
console.log(`😱 Axios request failed: ${error}`);
}
}

PUT Requests -

// Axios Put Call - MockablePut.
export const mockablePutData = () =>{
try {
const response = await putAPICall('mockablePostUrl', {
posted_data: 'example' });
console.log('👉 Returned data:', response.data);
}
catch (error) {
console.log(`😱 Axios request failed: ${error}`);
}
}

DELETE Requests -

// Axios Delete Call - MockableDelete.
export const mockableDeleteData = () =>{
try {
const response = await deleteAPICall('mockablePostUrl');
console.log('👉 Returned data:', response.data);
}
catch (error) {
console.log(`😱 Axios request failed: ${error}`);
}
}

React Component —

import React from 'react';
import { getJokeCategorieData, mockablePostData, mockablePutData, mockableDeleteData } from '../Datalayer/datalayerUtilities';
class App extends Component{
constructor(props){
super(props);
this.state = {
ListOfJokeCatgories: "",
isLoading: true,
}
}
handlerListOfJokesCategories = async() => {
const responseData = await getJokeCategorieData();
this.setState({
ListOfJokeCatgories: responseData.data,
isLoading: false
});
}
componentDidMount(){
this.handlerListOfJokesCategories();
}

render(){
return (
<div className="container">
{ this.state.isLoading ?
<div>Loading.....</div>
:
// Render your api call logic here...
}
</div>
)
}
}
export default APP;

Conclusion

Handling requests in React with Axios is extremely easy to know. There’s room for improvement, like adding more abstractions and structure, but that’s for an additional time.

What does one believe using React and Axios? Are there any certain features does one thinks I missed or should be covered? Let me know within the comments below!

--

--

Ishwar Deoolkar
Nerd For Tech

Frontend Developer @Jeeves || jQuery || ReactJs Developer || VueJs Developer || Angular Developer || Software Engineer || GraphQL || Redux and Recoil || VueX