Search code examples
javascriptreactjsdatatableprimereact

How can i implement lazyload in the primeReact?


I have a huge dataset thus i need to implement pagination for the Datatable in PrimeReact and for this i reffered the documentation which suggest to use lazyload to do so.But it is not working as well as my data is not displayed in the datatable but in console log it is getting displayed.

I have the following code implementation for achieving lazyload where i have added lazy attribute in the Datatable and called it onPage function using usestate in react.

Code:

import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { DataTable } from 'primereact/datatable';
import { Button } from 'primereact/button';
import { Column } from 'primereact/column';
import "primereact/resources/themes/lara-light-indigo/theme.css";     
    
//core
import "primereact/resources/primereact.min.css";

//icons
import "primeicons/primeicons.css";                 
import './App.css';

function App() {
const [data,setData]=useState([]);
const [loading, setLoading] = useState(false);
const [lazyState, setlazyState] = useState({
  first: 0,
  rows: 10,
  page: 1,
  sortField: null,
  sortOrder: null,
  filters: {
      name: { value: '', matchMode: 'contains' },
      'country.name': { value: '', matchMode: 'contains' },
      company: { value: '', matchMode: 'contains' },
      'representative.name': { value: '', matchMode: 'contains' }
  }});
  useEffect(()=>{
    console.log("use effect");
    getall();
    
  },[lazyState]);
  const getall=()=>{
    setLoading(true);
    axios.get("https://reqres.in/api/users").then((response)=>{
      setData(response.data);
     
    }).catch((error)=>{
      console.log(error);
    })
    setLoading(false);
  }
  const refresh=()=>{
    getall();
  }

  console.log(data)
   const header = (
    <div>
        <span className="display-6">Employees</span>
        <Button icon="pi pi-refresh" style={{marginLeft:'80%'}} rounded raised onClick={refresh}/>
    </div>
);
    
    const onPage=(event)=>{
      setlazyState(event);
    }
  return (
    <>
    <div className="container mt-5">
    <DataTable value={data.data} header={header} lazy paginator row={2} dataKey="id" rowsPerPageOptions={[2, 10, 25, 50]}  showGridlines tableStyle={{ minWidth: '60rem' }} totalRecords={data.total} onPage={onPage} loading={loading}>
    <Column field="first_name" header="Name"></Column>
    <Column field="email" header="Email-id"></Column>
    
  </DataTable>
  </div>
    </>
  );
}

export default App;


Solution

  • Working Code Sandbox demo of Lazying loading: https://codesandbox.io/s/primereact-demo-forked-m5yyhf