How to use the axios http client in React useEffect hook?

Estimated read time 2 min read

To use the axios HTTP client in a useEffect hook in React, you can make an HTTP request to an API endpoint and update the state of your component with the response data.

Here’s an example of how to use axios in a useEffect hook:

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

function MyComponent() {
  const [data, setData] = useState([]);

  useEffect(() => {
    axios.get('https://jsonplaceholder.typicode.com/posts')
      .then(response => {
        setData(response.data);
      })
      .catch(error => {
        console.error(error);
      });
  }, []);

  return (
    <div>
      <h1>Posts</h1>
      <ul>
        {data.map(item => (
          <li key={item.id}>{item.title}</li>
        ))}
      </ul>
    </div>
  );
}

export default MyComponent;

In this example, we’re defining a MyComponent that uses axios to fetch data from the JSONPlaceholder API. We’re using the useState hook to define a data state variable that starts as an empty array. In the useEffect hook, we’re making a GET request to the API endpoint and updating the data state variable with the response data.

To render the fetched data in our component, we’re rendering an unordered list of post titles using the data state variable.

Note that we’re passing an empty array as the second argument to the useEffect hook, which means that the hook will only run once when the component mounts. This is a common pattern for making one-time API requests in React components.

With this approach, you can use axios to fetch data from APIs in your React app and update the state of your components with the response data.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply