Using Axios in ReactJS

Luis Castillo
2 min readDec 27, 2021

What is Axios?

Axios is an HTTP client library that allows you to make requests to a given endpoint.

A promise-based HTTP client for the browser and node.js. Axios provides a simple to use library in a small package with a very extensible interface.

What makes Axios Great?

The library Axios make neater and use less code to perform many actions. These are some reasons what Axios is great.

  1. It has good defaults to work with JSON data. Unlike alternatives such as the Fetch API, you often don’t need to set your headers. Or perform tedious tasks like converting your request body to a JSON string.
  2. Axios has function names that match any HTTP methods. To perform a GET request, you use the .get() method.
  3. Axios does more with less code. Unlike the Fetch API, you only need one .then() callback to access your requested JSON data.
  4. Axios has better error handling. Axios throws 400 and 500 range errors for you. Unlike the Fetch API, where you have to check the status code and throw the error yourself.

How to Install Axios in ReactJS?

Installing Axios is very simple all you need to do in your terminal is:

$ npm install axios

This will give you the dependencies in your package.json

How to make a get request using Axios in Reactjs?

axios.get('homeUrlEnpoint')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
});

Async/await:

async function getTutorial() {
try {
const response = await axios.get('homeUrlEnpoint');
console.log(response);
} catch (error) {
console.error(error);
}
}

For documentation for Axios it can be found here through this link,

https://axios-http.com/docs/intro

--

--