Corporate Training
Request Demo
Click me
Menu
Let's Talk
Request Demo

Tutorials

API Integration with Axios

API Integration with Axios in React

Axios is a popular JavaScript library used for making HTTP requests in web applications. It is commonly used for API integration in React applications to fetch data from external sources, such as RESTful APIs. Here's how to use Axios for API integration in React:

1. Installation:

  • Start by installing Axios as a dependency in your React project:
npm install axios

 

2. Import Axios:

  • In your React component file where you want to make API requests, import Axios:
    import axios from 'axios';
 

 

3. Making GET Requests:

  • You can make a GET request to fetch data from an API endpoint. Axios returns a promise, so you can use .then() to handle the response.
axios.get('https://api.example.com/data')
  .then((response) => {
    console.log('Data:', response.data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });
     

 

4. Making POST Requests:

  • To send data to an API using a POST request, you can provide a data object as the second argument.
const data = {
  username: 'example',
  password: 'password123',
};

axios.post('https://api.example.com/login', data)
  .then((response) => {
    console.log('Response:', response.data);
  })
  .catch((error) => {
    console.error('Error:', error);
  });
       

 

5. Handling Responses:

  • Axios returns a promise that resolves to a response object. You can access the response data using response.data.

6. Handling Errors:

  • You can use .catch() to handle errors. Axios will reject the promise if the request encounters an error, such as network issues or a non-2xx HTTP response.

7. Asynchronous API Calls in React Components:

  • In a React component, you typically make API calls within lifecycle methods (e.g., componentDidMount in class components) or within a useEffect hook in functional components.
     import React, { useEffect, useState } from 'react';
import axios from 'axios';

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

  useEffect(() => {
    axios.get('https://api.example.com/data')
      .then((response) => {
        setData(response.data);
        setLoading(false);
      })
      .catch((error) => {
        console.error('Error:', error);
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      {data.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
}

export default MyComponent;
 

 

8. Axios Interceptors (Optional):

  • Axios allows you to set up request and response interceptors globally. You can use these interceptors to add headers, handle authentication, or perform other common tasks for all requests and responses.

9. Configuring Defaults (Optional):

  • You can set default configuration options for Axios, such as a base URL or default headers, using axios.defaults.