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

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

const EmployeelistFun = () => {
    const [employeeslist, setemployees] = useState(null)
    useEffect(() => {
        getemployees()
    }, [])
    const getemployees = () => {
        fetch(" http://restapi.adequateshop.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

import React from 'react';

class Employeelist extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            employees: [],
            IsApiError: false
        }
    }
    componentDidMount() {
        fetch(" http://restapi.adequateshop.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:

The post React Js- Fetch data from API using hooks appeared first on Software Development | Programming Tutorials.



Read More Articles