Let's Talk About Axios and how to use it in our project

Abarah LawenceAbarah Lawence
1 min read

Axios is a third-party and promised-based javascript library that is used to send HTTP requests. It is an alternative to the fetch() function.

Where do we make HTTP requests?

In a class component, requests are made in the componentDidMount() lifecycle while in a functional component, requests are made in react lifecycle hooks i.e. useEffect().

To use Axios, Axios needs to be installed in your project and imported in the component you want to fetch data in. We install using npm install axios in the command prompt.

Axios supports several request methods such as get, post, put, and delete.

Let's Fetch data in Axios Using the Get method

import { useEffect } from 'react';
import axios from 'axios';

const url = 'https://api.github.com/users';

const FirstRequest = () => {
  const fetchData = async () => {
    try {
      const response = await axios(url);
      const data = response.data;
      console.log(data);
    } catch (error) {
      console.log(error.response);
    }
  };

//Here we call the fetchData inside our useEffect
  useEffect(() => {
    fetchData();
  }, []);

  return <h2 className='text-center'>first request</h2>;
};
export default FirstRequest;

Thank you for reading....

0
Subscribe to my newsletter

Read articles from Abarah Lawence directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Abarah Lawence
Abarah Lawence

I am a Software Engineer from Lagos, Nigeria.