While employing PrimeReact, I encountered challenges related to the backend pagination of their data table. During these instances, I resorted to employing front-end pagination as a workaround. However, I have since developed a streamlined solution for backend pagination using my custom functions. The PrimeReact documentation lacked clarity on fetching data with a personalized style, prompting me to construct a dedicated function. Below, I outline the step-by-step process for implementing this solution.
*Step 1: Define your necessary states Here, i use my own style *
import data table from prime react into your react component
import {Column} from "primereact/column";
import {DataTable} from "primereact/datatable";
*Step2: fetch data with your UseEffect function *
*Final Step: Show your data into prime react data table *
*Here is my full code : *
`import React, {useEffect, useRef, useState} from "react";
import {Column} from "primereact/column";
import {DataTable} from "primereact/datatable";
import {baseUrl, checkAvailability} from "../../Helper/helper";
import useData from "../../hooks/useData";
import "./Clients.css";
const Clients = () => {
const {token} = useData().store;
const [loading, setLoading] = useState(false);
const {authPermissions} = useData().permissions;
const [first, setFirst] = useState(1);
const [rows, setRows] = useState(12);
const [clientData, setClientData] = useState()
const [totalRecords, setTotalRecords] = useState(0);
useEffect(() => {
//permination setup
const IsGetClient = checkAvailability(authPermissions, "get-client-list");
if (!IsGetClient) {
return;
}
//make a options which i send with fetch function
const options = {
method: "GET",
headers: new Headers({'content-type': 'application/json', Authorization: `Bearer ${token}`}),
};
const fetchRange = (page, pageSize) => {
setLoading(true)
let pages = (page / pageSize) + 1
fetch(`https://sltm.selopia.com/api/clients?page=${pages.toFixed(0)}&per_page=${pageSize}`, options).then((response) =>
response.json()).then(data => {
console.log(data);
setClientData(data?.data)
setTotalRecords(data?.data?.total)
setLoading(false);
});
}
fetchRange(first, rows);
}, [authPermissions, first, rows]);
return (
<div>
<DataTable
value={clientData?.data}
lazy
first={first}
dataKey="id"
paginator
rows={rows}
totalRecords={totalRecords}
loading={loading}
onPage={(e) => {
setFirst(e.first);
setRows(e.rows);
}}
// rowsPerPageOptions={[10, 20, 50, 100, 200, 500, 1000, 1309]}
tableStyle={{minWidth: '50rem'}}>
<Column field="id" header="ID"></Column>
<Column field="company" header="Company"></Column>
<Column field="phone_no" header="Phone"></Column>
</DataTable>
</div>
);
};
export default Clients;
`
Top comments (0)