How to Use Axios in React — Complete Guide

Wed Sep 21 2022

7 min read

Axios is one of the most popular ways of fetching APIs in React. Here is a complete guide to using Axios in your React projects.

Most web applications require fetching data from APIs at some stage in their development. For React-based projects, Axios is a promising all-in-one package that enables data fetching. This guide will cover everything you need to learn about using Axios in your React projects.

What is Axios?

There are many different ways of making API calls in your React applications. You can choose either the built-in fetch API or third-party libraries. In the latter case, Axios is one of the most popular data fetching packages available on npm.

Axios is an open-source, promise-based HTTP client. It uses JavaScript’s promises to send HTTP requests and manage their responses. Moreover, it offers additional features for fetching APIs that are not available in the basic Fetch API. Some of these features include:

  • Request interceptors.
  • Custom instances.
  • Request timeouts and cancellations.

How to Use Axios in React?

We must ensure the following things before using Axios in React.

  1. A React project.
  2. Axios installation.
  3. An API.

1. Creating a React Project

In case you don’t have an existing React project, create one using the following command:

sh
# Create a new React project
npx create-react-app axios-react-project
# Navigate and start the project server
cd axios-react-project
npm start

2. Installing Axios

You can install Axios using npm or yarn in your project directory.

sh
npm install axios

Once installed, import it into your JavaScript file like this:

js
import axios from 'axios';

3. Finding an API

We need the API’s endpoint URL to fetch data from it. If you don’t have an API to request, try RapidAPI Hub. It has thousands of APIs for different categories like weather, finance, travel, sports and what not. For this guide, I will be using the Random Quotes API as an example. It returns a random quote every time you send an API request.

Making an Axios API Request in React

Before diving into details, let’s start with a quick example request to this API. The basic syntax for an Axios GET request looks like this:

js
import axios from 'axios';
const requestAPI = async () => {
try {
const res = await axios.get(`API_URL`, {
headers: {},
params: {}
});
} catch (err) {
console.log(err);
}
};

After adding the endpoint URL, headers, and parameters of our API call, it turns out like this:

js
import axios from 'axios';
const fetchQuotes = async () => {
try {
const res = await axios.get(
`https://famous-quotes4.p.rapidapi.com/random`,
{
headers: {
'x-rapidapi-host': 'famous-quotes4.p.rapidapi.com',
'x-rapidapi-key': API_KEY
},
params: {category: 'all', count: '1'}
}
);
} catch (err) {
console.log(err);
}
};

Here is what the API response looks like:

json
[
{
"id": 13190,
"text": "So long as the memory of certain beloved friends lives in my heart, I shall say that life is good.",
"category": "good",
"author": "Helen Keller"
}
]

How to Trigger API Requests in React?

The fetchQuotes function will request the API using Axios. In React, we can trigger this function in a couple of different ways such as:

  • Event Handlers
  • useEffect Hook

1. Event Handlers

We can use event handlers like onSubmit and onClick to trigger the Axios requests. The following code will trigger the request using onClick.

js
import axios from 'axios';
import { useState } from 'react';
export default function Quotes() {
// State to store the quote
const [response, setResponse] = useState(null);
const fetchQuotes = async () => {
try {
const res = await axios.get(`https://famous-quotes4.p.rapidapi.com/random`, {
headers: {
'x-rapidapi-host': 'famous-quotes4.p.rapidapi.com',
'x-rapidapi-key': API_KEY,
},
params: { category: 'all', count: '1' },
});
// Set the response to the state.
setResponse(res.data);
} catch (err) {
console.log(err);
}
};
return (
<div>
<button onClick={() => fetchQuotes()}>Get Random Quote</button>
{
// If the response is not null, display the quote.
response && <span>{response.text}</span>
}
</div>
);
}

2. useEffect Hook

The useEffect Hook is used to run some functions during a component's lifecycle, such as running a function on a page’s first load or calling a function whenever a state changes. Here is a code example of triggering the Axios request using this hook.

js
import axios from 'axios';
import { useState, useEffect } from 'react';
export default function Quotes() {
const [response, setResponse] = useState(null);
const fetchQuotes = async () => {
try {
const res = await axios.get(`https://famous-quotes4.p.rapidapi.com/random`, {
headers: {
'x-rapidapi-host': 'famous-quotes4.p.rapidapi.com',
'x-rapidapi-key': API_KEY,
},
params: { category: 'all', count: '1' },
});
setResponse(res.data);
} catch (err) {
console.log(err);
}
};
useEffect(() => {
// Trigger the API Call
fetchQuotes();
}, []);
return (
<div>
{
// If the response is not null, display the quote.
response && <span>{response.text}</span>
}
</div>
);
}

Axios provides a function for each HTTP method, like the axios.get we used above. Let’s cover these functions separately.

How to Make an Axios GET Request?

We can use the axios.get function to make GET requests.

js
axios.get(url, config)

An Axios GET request looks like this in code:

js
const response = await axios.get('https://rapidapi.com/learn/api/rest');
console.log(response.data);

Try it yourself in this interactive component to see the response.

Loading component...

How to Make an Axios POST Request?

POST requests are used to send data to the API. We can use the axios.post function to make POST requests.

js
axios.post(url, data, config)

An Axios POST request looks like this in code:

js
const response = await axios.post('https://rapidapi.com/learn/api/rest', {
first_name: 'John',
last_name: 'Doe',
});
console.log(response.data);

Try it yourself in this interactive component to see the response.

Loading component...

How to Make an Axios PUT Request?

PUT requests are used to update a resource. We can use the axios.put function for these requests.

js
axios.put(url, data, config)

An Axios PUT request looks like this in code:

js
const response = await axios.put('https://rapidapi.com/learn/api/rest/1', {
first_name: 'Jane',
last_name: 'Doe',
});
console.log(response.data);

Try it yourself in this interactive component to see the response.

Loading component...

How to Make an Axios DELETE Request?

DELETE requests are used to delete a resource. We can use the axios.delete function for these requests.

js
axios.delete(url, config)

An Axios DELETE request looks like this in code:

js
const response = await axios.delete('https://rapidapi.com/learn/api/rest/1');
console.log(response.data);
Loading component...

How to Handle Errors With Axios?

To handle errors in a standard API call using Axios, we use a try...catch block. Inside the block, we can use the error object returned by Axios to log the errors. Here is an example:

js
try {
const res = await axios.get(`https://famous-quotes4.p.rapidapi.com/random`);
} catch (error) {
if (error.response) {
// Request made but the server responded with an error
console.log(error.response.data);
console.log(error.response.status);
} else if (error.request) {
// Request made but no response is received from the server.
console.log(error.request);
} else {
// Error occurred while setting up the request
console.log('Error', error.message);
}
}

For more explanation on error handling, you can check out our detailed guide on error handling with Axios.

Wrap Up

You are all set to use Axios for managing API requests in your React projects. Check out all our Axios guides here if you want to read more about it.