API Integration-React

By Published Updated 4 min read

In today’s web development landscape, integrating external services and data into your applications is a common and essential task. To achieve this, you need a strong understanding of making HTTP requests, handling responses, and working with asynchronous data.
we’ll dive into the world of API integration, focusing on two crucial aspects: making HTTP requests using Axios or the Fetch API and handling asynchronous data in components.

Making HTTP Requests

Understanding the Basics

Before we delve into specific tools and libraries, it’s essential to grasp the fundamentals of making HTTP requests. At its core, an HTTP request is a means of communicating with a remote server to retrieve or send data. You may need to fetch information from a RESTful API, submit a form, or communicate with other services.

Fetch API

The Fetch API is a modern and powerful tool for making HTTP requests in JavaScript. It provides a clean and straightforward way to interact with web services. Here’s a basic example of how to make a GET request using Fetch:

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    // Use the data in your application
  })
  .catch(error => {
    // Handle errors
  });Code language: JavaScript (javascript)

Axios

Axios is another popular library for making HTTP requests. It offers a more extensive feature set and better error handling compared to Fetch. Here’s an example of making a GET request with Axios:

import axios from 'axios';

axios.get('https://api.example.com/data')
  .then(response => {
    // Handle the response data
  })
  .catch(error => {
    // Handle errors
  });Code language: JavaScript (javascript)

When choosing between Fetch and Axios, consider your project’s requirements. Fetch is built into modern browsers, making it a good choice for lightweight applications. Axios, on the other hand, provides more advanced features and is a popular choice in larger, complex projects.

Making POST Requests

While GET requests are used for retrieving data, POST requests are essential for sending data to a server. Whether you’re submitting a form or sending data to an API, you can use the Fetch API or Axios for this purpose.

Here’s an example of making a POST request with the Fetch API:

fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ key: 'value' }),
})
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle errors
  });Code language: JavaScript (javascript)

And with Axios:

import axios from 'axios';

axios.post('https://api.example.com/data', { key: 'value' })
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle errors
  });Code language: JavaScript (javascript)

Authentication and Headers

In many cases, you’ll need to send authentication tokens or custom headers with your requests. Both Fetch and Axios allow you to customize headers, making it possible to handle authentication and other requirements. Here’s how you can add headers in Axios:

axios.get('https://api.example.com/data', {
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN',
    'Custom-Header': 'Header-Value',
  },
})Code language: JavaScript (javascript)

And for Fetch:

fetch('https://api.example.com/data', {
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN',
    'Custom-Header': 'Header-Value',
  },
})Code language: JavaScript (javascript)

Handling Asynchronous Data in Components

In a modern web application, it’s rare to work with data synchronously. You often need to fetch data from an API, and until the response is received, your application should remain responsive. Here’s how you can handle asynchronous data in components.

Using Promises

Promises are a fundamental concept for handling asynchronous operations in JavaScript. Both Fetch and Axios use promises to handle HTTP requests. You can use the then and catch methods to work with the data and handle errors, respectively. This allows you to maintain a responsive UI while waiting for the data to arrive.

axios.get('https://api.example.com/data')
  .then(response => {
    // Handle the response data
  })
  .catch(error => {
    // Handle errors
  });Code language: JavaScript (javascript)

Async/Await

Async/await is a more recent addition to JavaScript that simplifies working with promises, making your code more readable. Here’s how you can use async/await with Axios:

import axios from 'axios';

async function fetchData() {
  try {
    const response = await axios.get('https://api.example.com/data');
    // Handle the response data
  } catch (error) {
    // Handle errors
  }
}Code language: JavaScript (javascript)

State Management

When working with data in components, it’s crucial to manage the component’s state properly. Frameworks like React provide built-in state management features that make handling asynchronous data more manageable. For instance, you can use React’s useState and useEffect hooks to update the component’s state and trigger re-renders when the data changes.

Using Fetch Api

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

function DataComponent() {
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);
    const API = 'https://jsonplaceholder.typicode.com/users';
    useEffect(() => {
        fetch(API).then((result) => {
            result.json().then((res) => {
                console.log(res)
                setData(res);
                setLoading(false)
            }).catch((error) => {
                setLoading(false);
            })
        })
    }, []);

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

    return (
        <div>
            <table border={1}>
                <thead>
                    <tr>
                        <th>User Id</th>
                        <th>Name</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody>
                    {data.map(item => (
                        <tr key={item.id}>
                            <td>{item.id}</td>
                            <td>{item.name}</td>
                            <td>{item.email}</td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    );
}

export default DataComponent;Code language: HTML, XML (xml)

Output

API Integration Fetch Api

Using Axios :

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

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

    useEffect(() => {
        axios.get('https://jsonplaceholder.typicode.com/users')
            .then(response => {
                setData(response.data);
                setLoading(false);
            })
            .catch(error => {
                // Handle errors
                setLoading(false);
            });
    }, []);

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

    return (
        <div>
            <table border={1}>
                <thead>
                    <tr>
                        <th>User Id</th>
                        <th>Name</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody>
                {data.map(item => (
                    <tr key={item.id}>
                        <td>{item.id}</td>
                        <td>{item.name}</td>
                        <td>{item.email}</td>
                    </tr>
                ))}
                </tbody>
            </table>
        </div>
    );
}

export default DataComponent;Code language: JavaScript (javascript)

Output :

API Integration example

Conclusion

API integration is a critical skill for any web developer. Understanding how to make HTTP requests using tools like Fetch and Axios and managing asynchronous data in components is essential for building robust and responsive web applications. By mastering these techniques, you’ll be well-equipped to create dynamic and data-driven web experiences.

Incorporating API integration into your web development toolkit opens up a world of possibilities, allowing you to connect your applications with a vast array of services and data sources. Whether you’re building a simple personal project or a complex enterprise application, the ability to work with APIs is a valuable asset that can enhance the functionality and user experience of your web applications.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume