Blog /

Axios to consume REST API in React

javascript

Axios to consume REST API in React

March 23, 20236 minutes
Axios to consume REST API in React

Introduction

Today, most applications build consume data from an API. These API centric applications have various ways and technologies used to make requests to the API. How do you consume API in your Application? What Technologies do you use?
In this article, we will be looking at Axios, a third-party promise-based HTTP Client library for node.js and the browser. We will be looking at how to use Axios to make HTTP requests to an API. We will also be looking at how to handle errors when making HTTP requests.

interesting

What is Axios

Axios is a third-party promise-based HTTP Client library for node.js and the browser. It is isomorphic (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js http module, while  the client (browser) uses XMLHttpRequests.
Axios can add to your project either via a Content Distribution Network or CDN, or install it via a package manager, like npm or yarn. Axios can run within a browser or a node.js environment.

Why Axios

??

It is a very popular library for making HTTP requests. It is very easy to use and has a lot of features.
It is also very popular in the React community. It is used in many React projects.  Personally, Bellow are a few significant advantages of Axios over the traditional Fetch API.

  • When sending requests, Axios automatically signifies the data, but Fetch API requires that you do it manually.
  • Axios has better error handling than the Fetch API. Error handling with Axios is better because bad responses (such as 404 or 500) will end up causing the Promise to be rejected by throwing an exception. It can throw errors from the ranges of 400 to 500. These errors can easily be handled using the try-catch block.
  • Axios allows cancelling requests and request timeouts. It has a cancel token that can be used to cancel a request.

Getting started

To get started, you need to install Axios in your project. You can do this by running the following command in your project.

npm install axios

Once this is done, you can import Axios in your project and start making requests.

import axios from 'axios';

axios.get('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => {
    console.log(response);
  })
  .catch(error => {
    console.log(error);
  });

In the above code, we are making a GET request to the API. We are using the get method of the axios object to make the request. The get method takes in the URL of the API as the first argument. The second argument is an object that contains the request configuration. The third argument is a callback function that is called when the request is successful. The fourth argument is a callback function that is called when the request fails. The callback functions are optional. You can also use the then and catch methods to handle the response and errors respectively.

For easy use, I always create an Axios instance and use it to make requests. This is because I can set the base URL of the API and the headers for all requests. This makes it easy to make requests to the API. Below is an example of how to create an Axios instance.

Create a file in your SRC directory of your react project and name it client.js. This file will contain the Axios instance.

Use the .create() method of the Axios object to create an Axios instance. The .create() method takes in an object as an argument. The object contains the configuration for the Axios instance. The configuration object can contain the following properties.

The baseURL property is the base URL of the API. This is the URL that will be used for all requests. The headers property is an object that contains the headers for all requests. The headers object can contain any number of headers. The headers object is optional. You can also set the headers for each request.


// src/client.js
import axios from 'axios';

const Client = axios.create({
  baseURL: 'https://jsonplaceholder.typicode.com', // base URL of the API
  headers: {
    'Content-Type': 'application/json',
  },
});

export default Client;

Making Request

To make a request, you need to import the Axios instance and use it to make the request. Below is an example of how to make a request using the Axios instance.

import Client from './client';

const App = () => {
  const [todos, setTodos] = useState([]);

  useEffect( async () => {
    const {data} = await Client.get('/todos');
    setTodos(data);
  }, []);

  return (
    <div>
      <h1>Todos</h1>
      <ul>
        {todos.map(todo => (
          <li key={todo.id}>{todo.title}</li>
        ))}
      </ul>
    </div>
  );
};

In the above code, we are making a GET request to the API. We are using the get method of the Axios instance to make the request. Here, the endpoint /todos is used as the URL since the instance has the base URL set already.

Handling Errors

It is typically advised that we manage errors while consuming data from an API to assist identify the sort of error we receive. These failures could be as a result of sending inaccurate data, sending the wrong API the request, or encountering a network issue.

We can handle errors in Axios by using the .then() and .catch() methods, or by using the try...catch block for async/await Axios requests.

Below is an example of how to handle errors using the try and catch block.

import Client from './client';

const App = () => {
    const [todos, setTodos] = useState([]);
    const [error, setError] = useState(null);

    useEffect( async () => {
    try {
        const {data} = await Client.get('/todos');
        setTodos(data);
    } catch (error) {
        setError(error);
    }
    }, []);

};

Conclusion

In this article, we looked at Axios, a third-party promise-based HTTP Client library for node.js and the browser. We looked at how to use Axios to make HTTP requests to an API. We also looked at how to handle errors when making HTTP requests.

Happy Hacking!

gif

Bentil here🚀
Have you used Axios before? What do you think about it? Let me know in the comments section below.

Kindly Like, Share and follow us for more.

Explore other topics