Categories
React

How to Use the Axios HTTP Client in React useEffect Hook?

Spread the love

In many situations, we need to make HTTP requests in our code to get or submit data in our React components.

Axios is a popular HTTP client library that we can use to make HTTP requests easily.

In this article, we’ll look at how to use the Axios HTTP client with the useEffect hook to make HTTP requests.

Use the Axios HTTP Client with the React useEffect Hook

We can make HTTP requests when the component mounts by calling the useEffect hook with an empty array in the 2nd argument.

For instance, we can write:

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

export default function App() {
  const [data, setData] = useState([]);

  const getData = async () => {
    const { data } = await axios.get(`https://yesno.wtf/api`);
    setData(data);
  };

  useEffect(() => {
    getData();
  }, []);

  return <div>{JSON.stringify(data)}</div>;
}

We define the getData function to make a GET request with the axios.get method.

The function is async since axios methods return a promise.

We just pass in a URL to make a GET request.

We’ve to define the getData function outside the useEffect hook since the useEffect callback should be a synchronous function.

The empty array in the 2nd argument means that we make the request only when the component mounts.

We call setData to set the data state and we render the data in the JSX code.

If we want to make HTTP requests when a state or prop changes, then we should pass those into the array in the 2nd argument.

Using the axios-hooks Library

We can also use the axios-hooks library to let us make request with a custom hook that uses the Axios library.

To use it, we install it by writing:

npm install axios axios-hooks

Then we write:

import React from "react";
import useAxios from "axios-hooks";

export default function App() {
  const [{ data, loading, error }, refetch] = useAxios("https://yesno.wtf/api");

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error!</p>;

  return <div>{JSON.stringify(data)}</div>;
}

We call useAxios to return an array with an object that has the data , loading , and error properties.

data has the response data.

loading has the loading state. It’s true if the request is loading.

error has the error state. It’s true if the request results in an error.

We can call the refetch function to make the request again.

Conclusion

To use Axios with the useEffect hook, we just define an async function and call it inside the useEffect callback.

Alternatively, we can use the useAxios hook provided by the axios-hooks library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *