[Simple Way]-Fetch Data From API and Display In Table React Js


 In this post, we are going to discuss Fetch data from API and display it in table React Js using a bootstrap HTML table.

In react, we have two component types, functional component and class component,Functional components are literally JavaScript functions, they return HTML, which describes the UI, for example, a function called “functionalcomp”, which returns, and tag that says “Hello this is a functional Component”.

function functionalcomp() {
return Hello this is a functional Component
}

Class, components, on the other hand, are regular ES6 classes that extend the component class from React the library.they must contain a render method, which in return HTML, for example, class Myclasscomp extends React. Component and the class contain a render method which returns tag that says “Hello this is my class Component”.

class Myclasscomp extends React.Component {
render() {
return Hello this is a my class Component
}
}

In this example, we will discuess both i,e functional component and class component for showing the data .So let’s start.

In this post we will discuss the below points

  • Fetch User Data from API and add to table using ReactJS
  • Displaying data from fetch API using React Js
  • How to fetch API data and show that on table form in react.js
  • How to display data from API in react js using fetch API

How to fetch data from API in React js using Fetch API

Step 1 – Create React App

Step 2 – Create components for showing List data

Create two folders called components in the src folder and two components inside that i.e EmployeelistFun.js and Employeelist.js 

fetchdatafromapi

Step 3 – Integrate Rest API using fetch() function

React js fetch data from API example

The Fetch API is the latest interface that allows us to make HTTP requests to Rest APIs from the client-side.

If you know about with XMLHttpRequest (XHR) object, then let you know that the Fetch API can perform all the tasks as the XHR object can do.

 

The fetch() function is available in the global scope that guides the web browser’s client to send a request to a rest URL.

Sending a Request and Reading the Response
The fetch() method takes only one parameter which is the URL of the resource i. e API endpoint that you want to fetch.

const response = (url) => {
    fetch(url)
      .then((res) => res.json())
      .then(
        (result) => {
          console.log(result);
        },
        (error) => {
          console.log(error)
        }
      );
  };

and the Fetch API is very simpler and cleaner to use, Fetch API uses the Promise to produce more flexible features to make requests to servers from the client.

React Js fetch data from API functional component

EmployeelistFun.js

Functional Component Definition:

The getemployees function is defined to make a GET request to the specified API endpoint (http://samplerestapi.com/api/Metadata/GetEmployees). Upon successful response, the JSON data is extracted and stored in the state variable employeeslist using the setemployees function. 

If employeeslist is null, it renders a message saying "No Record Found". This is to handle the case when data hasn't been fetched yet or if there's an error fetching the data.

If employeeslist contains data, it renders a table displaying the list of employees. It maps through the employeeslist array and generates a table row for each employee, displaying their id, name, address, city, and zip code.The EmployeelistFun component is exported as the default export, making it available for use in other parts of the application.Below component fetches a list of employees from an API and displays them in a table format. It handles loading states and errors gracefully using hooks provided by React.

import React, { useState, useEffect } from "react"

const EmployeelistFun = () => {
const [employeeslist, setemployees] = useState(null)
    useEffect(() => {
        getemployees()
    }, [])
const getemployees = () => {
        fetch(" http://samplerestapi.com/api/Metadata/GetEmployees")
            .then(res => res.json())
            .then(
                (result) => {                    
                    setemployees(result)
                },
                (error) => {
                    setemployees(null);
                }
            )
    }
if (!employeeslist) return (<div>No Record Found</div>)
return (<div>
        <h2>Employees List Funcational Component </h2>
        <table className="table" >
            <thead>
                <tr>
                    <th>Employee Id</th>
                    <th>Name</th>
                    <th>Address</th>
                    <th>City</th>
                    <th>ZipCode</th>
                </tr>
            </thead>
            <tbody>
                {employeeslist.map(emp => (
                    <tr key={emp.Id}>
                        <td>{emp.Id}</td>
                        <td>{emp.Name}</td>
                        <td>{emp.Address}</td>
                        <td>{emp.City}</td>
                        <td>{emp.ZipCode}</td>
                    </tr>
                ))}
            </tbody>
        </table>
    </div>)
}
export default EmployeelistFun;

React fetch data from API Class component

Employeelist.js

Class Component Definition:The Employeelist class is defined, extending React.Component. This is a traditional way of defining components in React.

Constructor:The constructor method is used to initialize the component's state. It sets the initial state with an empty array for employees and a boolean flag IsApiError initialized to false.

ComponentDidMountcomponentDidMount is a lifecycle method provided by React. It's called after the component is mounted (inserted into the tree). Inside this method, a GET request is made to fetch employee data from the specified API endpoint. Upon successful response, the retrieved data is stored in the component's state under employees. If there's an error during the request, IsApiError is set to true.

The render method is used to define what the component should render based on its state and props. In this case, it first retrieves the employees list from the component's state.

If employeeslist is not empty and has a length greater than 0, it renders a table displaying the list of employees. Each employee's details such as id, name, address, city, and zip code are displayed in separate table cells.If employeeslist is empty or if there was an error fetching the data (indicated by IsApiError being true), it renders a message saying "No Record Found".

The Employeelist class component is exported as the default export, making it available for use in other parts of the application.


import React from 'react';

class Employeelist extends React.Component {
    constructor(props) {
        super(props);
this.state = {
            employees: [],
            IsApiError: false
        }
    }
    componentDidMount() {
        fetch(" http://samplerestapi.com/api/Metadata/GetEmployees")
            .then(res => res.json())
            .then(
                (result) => {
this.setState({
                        employees: result
                    });
                },
                (error) => {
this.setState({ IsApiError: true });
                }
            )
    }
    render() {
var employeeslist = this.state.employees;
        debugger;
if (employeeslist && employeeslist.length > 0) {
return (<div>
                <h2>Employees List Class Component</h2>
                <table className="table" >
                    <thead>
                        <tr>
                            <th>Employee Id</th>
                            <th>Name</th>
                            <th>Address</th>
                            <th>City</th>
                            <th>ZipCode</th>
                        </tr>
                    </thead>
                    <tbody>
                        {employeeslist.map(emp => (
                            <tr key={emp.Id}>
                                <td>{emp.Id}</td>
                                <td>{emp.Name}</td>
                                <td>{emp.Address}</td>
                                <td>{emp.City}</td>
                                <td>{emp.ZipCode}</td>
                            </tr>
                        ))}
                    </tbody>
                </table>
            </div>)
        }
else {
return (<div>No Record Found</div>)
        }
    }
}
export default Employeelist;

Step 4 – Import Component in App.js.
App.js

import logo from './logo.svg';
import './App.css';
import Employeelist from "./components/Employeelist";
import EmployeelistFun from "./components/EmployeelistFun";

function App() {
return (
    <div className="container">
      <Employeelist/>
      <EmployeelistFun/>
    </div>
  );
}

export default App;

React fetch data from API and display in table

I’m assuming that you are familiar with React Js framework and creating React Js applications. If not then please go through the following articles: