How To Use Axios With React JS: HTTP REQUESTS Using Axios🔥

How To Use Axios With React JS: HTTP REQUESTS Using Axios🔥

This article will show you exactly how to utilize Axios.js with React by providing dozens of real-world examples that use React hooks.

You'll learn why you should use Axios as a data fetching framework, integrate it with React, and use it to make an HTTP request.

Let's dive right in!

What is Axios:

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

This could be your external API or your own backend server API, By making a request, you expect your API to perform an operation according to the request you made.

If you make a GET request, for example, you expect to get data to show in your application.

Why We should use Axios in React:

Why use Axios when there are other libraries that can be used to perform these requests?

There are a few advantages of using Axios over other libraries and methods.

  1. Unlike Fetch, Axios doesn't require you to set headers or convert your request body to a JSON string yourself.

  2. Axios have function names that match HTTP methods. The .get() method is used to perform GET requests.

  3. Axios, the new HTTP client for JavaScript, can automatically respond to 401, 403, 404, and 500 errors. Unlike the Fetch API, the Ajax library from which it evolved, it does not have to be told to do so.

  4. With the Axios Promises Library, one .then() callback is all you need to access your requested JSON data.

  5. You can also cancel a request using CancelToken. The Axios cancel token API is based on the withdrawn cancelable promises proposal.

How to Set Up Axios with React:

It's a very simple process to just set up Axios in your react application, if you have already an existing project then you just need to execute the following steps.

  1. Install Axios with npm by using the command npm install axios.

  2. Then you will need an API endpoint for making your Requests.

Now, after all the setup with Axios with React, let's start implementing Axios GET request method.

How to make a GET Request:

We can make a GET request to get or fetch the data from the API.

When a component mounts, you can make use of the React Hook, useEffect, to make an API call. So, to execute an HTTP GET request, use axios.get() with a URL and callback, and attach .then() to the promise returned.

For Example, I am using an API that is News API, You can understand by looking at the example below:

import React, { useState } from "react";
import axios from "axios";

function App() {
  const api =
    "https://newsapi.org/v2/everything?q=tesla&from=2022-05-19&sortBy=publishedAt&apiKey=38e538bcdbb841ee90f66a85dd639224";

  const [news, setNews] = useState([]);

  React.useEffect(() => {
    axios.get(api).then((response) => {
      console.log(response);
      console.log(response.data.articles, "fd");
      setNews(response.data.articles);
    });
  }, []);

  console.log(news);

  return (
    <>
      <div>
        {news.map((item) => {
          return <div>{item.author}</div>;
        })}
      </div>
    </>
  );
}

export default App;

Now as we can see, The response is returned as an object . The data (a news post with author, name, description properties, etc) is put in a piece of state called news which is displayed in the component.

How to Handle Errors with Axios:

Now, See what if an error is encountered while making a call to the API, then how we can capture that. For example, if you have a network error or maybe you passed and entered some non-valid data, then we need to capture those errors.

We can handle errors very easily in Axios. In the below code, you can understand how you can implement error handling in Axios.

import React, { useState } from "react";
import axios from "axios";

function App() {
  const api =
    "https://newsapi.org/v2/everything?q=tesla&from=2022-05-19&sortBy=publishedAt&apiKey=38e538bcdbb841ee90f66a85dd639224";

  const [news, setNews] = useState([]);
  const [error, setError] = useState(null);

  React.useEffect(() => {
    axios
      .get(api)
      .then((response) => {
        setNews(response.data.articles);
      })
      .catch((error) => {
        setError(error);
      });
  }, []);

  console.log(news);

  if (error) {
    return (error.message, "Error found");
  }

  return (
    <>
      <div>
        {news.map((item) => {
          return <div>{item.author}</div>;
        })}
      </div>
    </>
  );
}

export default App;

Now see, If this condition is fulfilled, Axios will proceed to execute the .then() callback function. If not, it will run the .catch() callback function.

To indicate errors, we are putting the error data in the state. If there is an error, we will display the error message to our user.

Congratulations! You have learned one of the most powerful HTTP client libraries to power your applications.

You can check out my other articles as well on:

How To Create a React Form With Hooks

Conditional Rendering in ReactJS

JSX in React - Detailed Explanation with example

How and where to deploy your React App in less than 5 minutes..

What are Controlled and Uncontrolled Components in React JS? Which one to use?

Did you find this article valuable?

Support Nikhil Khandelwal by becoming a sponsor. Any amount is appreciated!

Â