API Integration with React js

Syed Muhammad Ali Raza - Nov 29 '23 - - Dev Community

Integrating APIs with React.js

React.js has become a force in the world of front-end development due to its component-based architecture, dynamic presentation, and living ecosystem. A key aspect of building dynamic and data-driven applications with React is integrating APIs to retrieve and manipulate data from external sources. In this article, we will explore the API integration process with React.js, covering the basics and providing practical coding examples.

Understand API integration

API (Application Programming Interface) integration allows different software systems to connect, communicate and share data. In the context of React.js, API integration usually means receiving and using data from an external source, such as a RESTful API or a GraphQL endpoint, to dynamically update the user interface.

Prerequisites

Before getting into the coding details, make sure you have Node.js and npm (Node Package Manager) installed on your device. You can create a new React app using this command:

npx create-react-app api-integrate-react
cd api-integration-react
Enter fullscreen mode Exit fullscreen mode

Get information with "Go".

In React, the fetch function is often used to make HTTP requests and retrieve data from the API. Let's create a simple component that receives and displays data from a hypothetical API.

// src/components/ApiDataComponent.js
import Reaction from Reaction { useState, useEffect;

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

  useEffect (() => {
    const fetchData = async() => {
      try {
        const response = await get('https://api.example.com/data');
        const result = await response.json();
        setData ( result );
      } catch (error) {
        console.error('Error retrieving data:', error);
      }
    };

    fetchData();
  }, []); // Activate the empty array to run montage once

  return (
    <div>
      <h1>API Information</h1>
      <ul>
        { data.map((element) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default ApiDataComponent;
Enter fullscreen mode Exit fullscreen mode

In this example, we use the "useState" hook to manage the data state and the "useEffect" hook to get the data when the component is installed. The received data is then displayed in a simple list.

Axios for HTTP requests

Although Getch is widely supported, some developers prefer to use third-party libraries such as Axios for a more exclusive and rich API. To use Axios, you must first install:

npm install axios
Enter fullscreen mode Exit fullscreen mode

Now modify the previous example to use Axios instead of "fetched":

// src/components/ApiDataComponent.js
import Reaction from Reaction { useState, useEffect;
import axios from 'axios';

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

  useEffect (() => {
    const fetchData = async() => {
      try {
        const response = await axios.get('https://api.example.com/data');
        setData(response.data);
      } catch (error) {
        console.error('Error retrieving data:', error);
      }
    };

    fetchData();
  }, []);

  return (
    <div>
      <h1>API Information</h1>
      <ul>
        { data.map((element) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default ApiDataComponent;
Enter fullscreen mode Exit fullscreen mode

Handle API responses

API often returns various status codes and data structures. Different scenarios should be approached politely. For example, you may want to display a loading indicator when data is being fetched, or display an error message when a request fails.

// src/components/ApiDataComponent.js
import Reaction from Reaction { useState, useEffect;
import axios from 'axios';

const ApiDataComponent = () => {
  const [data, setData] = useState ([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect (() => {
    const fetchData = async() => {
      try {
        const response = await axios.get('https://api.example.com/data');
        setData(response.data);
      } catch (error) {
        setError('Error getting data');
      } in the end {
        setLoading ( false );
      }
    };

    fetchData();
  }, []);

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

  return (
    <div>
      <h1>API Information</h1>
      <ul>
        { data.map((element) => (
          <li key={item.id}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
};

export default ApiDataComponent;
Enter fullscreen mode Exit fullscreen mode

The results

Integrating APIs with React.js is a key skill for building modern web applications. Whether you choose to use native fetch functions or third-party libraries like Axios, it's important to understand how to retrieve responses, handle responses, and update the state of your components. As you continue to work with APIs in your React projects, you will encounter several scenarios and challenges, however

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player