Datatable load from API data. Call API, Get Json Data, and Load in a datatable in React. Step by Step

 Here we will learn how to load a data table from database data in the React application. We won't connect to the database. We just connect API and collect data as JSON. Finally, We will load that JSON data into our data table.

What will we learn?

1. Datatable
2. Callback function
3. Axios for API call

Datatable
Datatable


Step 1. Collect data from API: To show data in Datatable, we must collect the data first. Here we are collecting data through API.  Given below the data flow structure of this example.

Data Flow
Data flow


  • In our component, we have used a callback function (getAllCategories). If data comes successfully then it's loading JSON data into the array type data variable of our component otherwise showing the error message.
  • In the controller, we just provide the API address to the API calling service.
  • Finally, the API service calls API, collects data, and pass up to components. We have used Axios to call the API.
Coding structure
Data flow in code

Step 2. Load into data table : Once the Array variable (data) is loaded from API, we have to parse that data into a data table. 

JSON Data Sample - 
{
    "results": [
        {
            "CategoryID": 1,
            "CategoryName": "Main Food",
            "Status": 1
        },
        {
            "CategoryID": 2,
            "CategoryName": "Drinks",
            "Status": 1
        },
    ]
}
Data table load
Finally load array data in a datatable

Here iterating a loop based on array records. And each array record value mapping to d. Finally parsing d.[json field name] to the data table.

Done


Code 👇

 Component
import { Toast } from "../Toast";
import '../../styles/AdminUIPage.css';
import { useEffect, useState } from "react";
function HomeCategoryPage() {
    const [data, setData] = useState([]);
    useEffect(() => {
        controller.getAllCategories(
            (data) => { setData(data); },
            (errorMessage) => { Toast(errorMessage, 'error'); }
        );
    }, []);
    return (
        <div className="table-responsive">
            <table className="table table-striped table-bordered nowrap">
                <thead>
                    <tr className="text-center">
                        <th>ID</th>
                        <th>Category</th>
                        <th className="d-none">StatusCode</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    {Array.isArray(data) && data.map((d, i) => ( // Map once data available
                        <tr key={i} className="text-center">
                            <td>{d.CategoryID}</td>
                            <td>{d.CategoryName}</td>
                            <td className="d-none">{d.Status}</td>
                            <td>{d.Status === 1 ? 'Active' : 'Inactive'}</td>
                            <td>
                                <button onClick={() => handleEdit(d, 'M')} className="btn btn-primary mr-2">Edit</button>
                                <button onClick={() => handleEdit(d, 'D')} className="btn btn-danger">Delete</button>
                            </td>
                        </tr>
                    ))}
                </tbody>
            </table>
        </div>
    )
}
export default HomeCategoryPage;

Controller - Callback funtion
import { getData, postData } from '../services/apiServices';
class MenuCategoryController {
    async getAllCategories(onSuccess, onError) {
        try {
            const data = await getData('http://localhost:8080/v1/category');
            console.log("data : "+ JSON.stringify(data));
            onSuccess(data);
        } catch (e) {
            console.log("Controller, Error : " + e);
            onError(e);
        }
    };
}
export default MenuCategoryController;

API Calling 
import axios from 'axios';
// Common function to fetch all data. Just pass URL here
export const getData = async(url)=>{
  try {
    const response = await axios.get(url);
    return response.data.results;
  } catch (error) {
    throw new Error('Error fetching data:', error);
  }
};
export default getData;

Post a Comment

0 Comments