How To map two API endpoints and filter new data in a React application?

To begin, you need to install React and follow the below steps.

  1. Install the required dependencies for this solution: Axios for API requests, and Material-UI for table display.
  2. Create a React component: Create a React component that will handle the data fetching and filtering. For example, create a component named DataFilterComponent.js.
  3. Fetch data from API endpoints: Use the useEffect hook to fetch data from both API endpoints when the component mounts. You can use axios or the native fetch API.
  4. Import the required modules and initialize the state in the functional component.
DataFilterComponent.js
import React, { useState, useEffect } from 'react';
import axios from 'axis';
import { Table, TableBody, TableCell, TableHead, TableRow, Paper } from '@material-ui/core';
import { PlaylistAddCheck } from '@material-ui/icons';

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

 useEffect(() => {
    fetchData();
 }, []);

 const fetchData = async () => {
    const result1 = await axios.get('https://api1.example.com/data');
    const result2 = await axios.get('https://api2.example.com/data');

    // Map the two APIs' data structures to match
    const mappedData = result1.data.map(item => {
      const matchedItem = result2.data.find(dataItem => dataItem.id === item.id);
      return {
        ...item,
        additionalField: matchedItem ? matchedItem.additionalField : '',
      };
    });

    setData(mappedData);
 };

 return (
    <Paper>
      <Table>
        <TableHead>
          <TableRow>
            <TableCell>ID</TableCell>
            <TableCell>Name</TableCell>
            <TableCell>Additional Field</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {data.map(item => (
            <TableRow key={item.id}>
              <TableCell>{item.id}</TableCell>
              <TableCell>{item.name}</TableCell>
              <TableCell>{item.additionalField}</TableCell>
            </TableRow>
          ))}
        </TableBody>
      </Table>
    </Paper>
 );
};

export default DataFilterComponent;

5. Finally, render the DataTable component in your application.

App.js
import React from 'react';
import DataTable from './DataTable';

const App = () => {
 return (
    <div>
      <h1>Data Table</h1>
      <DataTable />
    </div>
 );
};

export default App;