How to use axios in React

How to use axios in React

axios is a widely used JavaScript library for making HTTP requests simply and efficiently. When working with React, axios is a popular choice to handle API calls.

axios is a widely used JavaScript library for making HTTP requests simply and efficiently. When working with React, axios is a popular choice to handle API calls. Here's how you can use axios in React to get and send data from your server.

First, you'll need to install axios in your React project. You can do this by running the following command in your terminal:


npm install axios --save

You can use axios in your components as follows:


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

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

  useEffect(() => {
    axios.get('/api/data')
      .then(response => {
        setData(response.data);
      })
      .catch(error => {
        console.error(error);
      });
  }, []);

  return (
    <div>
      {data ? (
        <ul>
          {data.map(item => (
            <li key={item.id}>{item.name}</li>
          ))}
        </ul>
      ) : (
        <p>Loading data...</p>
      )}
    </div>
  );
};

export default MyComponent;

In this example, we have a component called MyComponent which uses the data state to store the data obtained from the GET request. We use the useEffect hook to make the request when the component is mounted. Once the data is received, it is displayed in a <ul> list.

In case the data is not yet available, the message "Loading data..." is shown. This is useful for managing the loading state when retrieving data from the server.

Remember to replace '/api/data' with the actual URL of your server.

This example gives you a starting point for using axios within a React component. You can extend this logic to handle other requests or implement more functionality in your React project.