Pages

How to Display the data in React.js?

 In this Blog, we are going to learn to display the data in React js. We will use React hooks, bootstrap , …..


Here is the image, what we will build at the end of the Blog.




<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">



We can also select the table from the bootstrap and add to the code.


Add the following code to the Dashboard..js file


To display the data, we will use “axios”.


First, create a function and under the function use “axios”. We will take the “Get” method and place a get url. 


The following line will return a promise -


axios.get("https://localhost:44395/api/Customer/TblCustomer")


And to handle the promise, we use “.then”. To store the data, we use “useState”. 


const [data, setData] = useState([]);


We set the data to store the data in “data”.


setData(res.data);


Whenever the page gets reloaded and the value changes, everytime function getData() will be called.


Then only we can see data. For this, we take help of “useEffect”.


useEffect in react is basically a hook that run whenever useState is run or the value changes.


useEffect(()=>{

    getData();

},[]);


Inside useEffect, call the getData() function to call everytime and to display the data.


import React from 'react'

import { Link } from 'react-router-dom';

import { useState, useEffect } from 'react';

import axios from 'axios';


const Dashboard = () => {


  const [data, setData] = useState([]);


  function getData() {

      axios.get("https://localhost:44395/api/Customer/TblCustomer")

      .then((res) => {

          console.log(res.data);

          setData(res.data);

      });

  }

  useEffect(()=>{

    getData();

},[]);


  return (

    <>

    <h2>Dashboard</h2>

    <table class="table">

  <thead>

    <tr>

      <th scope="col">Name</th>

      <th scope="col">Email</th>

    </tr>

  </thead>

  { data.map((eachData)=> {

    return(

        <>

        <tbody>

    <tr>

      <td>{eachData.name}</td>

      <td>{eachData.email}</td>

    </tr>

   </tbody>

        </>

    )

  })

}

</table>

</>

  )

}


export default Dashboard


No comments:

Post a Comment

Make new Model/Controller/Migration in Laravel

  In this article, we have included steps to create a model and controller or resource controller with the help of command line(CLI). Here w...