Skip to main content

Basic Pagination

Basic in a sense that you have data you want to pull from backend but they comply with pagination fomart.

There are few things you need to do this to achieve your task.

  1. Import Paginator and normalizePagination components.
import {
Paginator,
normalizePagination,
} from "../../../general-components/paginator";
  1. Initialize a hook for page numbers.
const [pages, setPages] = useState<any>({});
  1. Its recommended that when page loads you should pull the first page page=1
//loads first page on page render
let params = `organization_id=${organization_id}&page=1`;
//pull your data with usable function as below
const pullContracts = async (params?: string) => {
try {
setIsLoading(true);
let results = await contactsApi.pullAllContacts(params);
if (results) {
//normalizePagination Will help you set data into variables expected formart
normalizePagination(results, setContracts, setPages);
// setContracts(results);
}
} catch (ex) {
setContracts([]);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
pullContracts(params); //
}, []);
//now you have your contracts on variable contracts.
  1. Now how do we progress the pagination and how do we display the pagination links.

    The Paginator component will handle all these for you

it expects two parameters,

  • pages => which are links to the next page
  • callback => which will pass parameter of next selected page so you can do some thing about it like updating url and execute the pull data again codes below.
<Paginator
pages={pages}
callback={(pageNum: any) => {
//1. remove the prev page number from url
params = params.split("&page=")[0];
//2. append new page number
if (pageNum) {
params = `${params}&page=${pageNum}`;
}
//3. Lets call our function now
pullContracts(params);
}}
/>

normalizePagination in details

That was a joke. there is nothing special to this function except lets check its parameter

  • 1 is an remote source results from and end point
  • 2 is you pass in the setter function from react hook where you need your data to stay
  • 3 setPages for setting pages for pagination to work
  • 4 a call back for giving back the number of records found from backend its syntax as
normalizePagination(results, setContracts, (recourds_count) =>
console.log(records_count)
);