Skip to main content

Browser conscious pagination.

Pagination philosophy

Our philosophy towards pagination is that. our browser should know about pagination and respect them

Trackmis frontend decided that its pagination will be reflected with browser as well, i.e the browser back and next buttons will reflect on patination numbers ( page numbers ) as you navigate from one number to the other.

mis-pagination expects that our backend will spit out its json pagination-ready results or just plain list (array) of data.

mis pagination is abstracted on component called <Paginator /> now this component expects two parameters to work, pages and progressPage we'll get to this in a minute.

Take care

Paginator works by changing page numbers and update ?page URL parameter therefore forces page re-render this forces api call with new page number.

Page renders invokes useEffect which calls some async function to fetch data, the results will be fed into normalizePagination function with other parameter just to get pagination ready data from backend results.

ex.

const getAllAccounts = async (params?: string) => {
try {
setIsLoading(true);
let results = await api.pullAllAccount(params);
if (results) {
normalizePagination(results, setAccounts, setPages);
}
} catch (ex) {
console.log(ex);
setAccounts([]);
} finally {
setIsLoading(false);
}
};

Lets breakdown this code.

let results = await api.pullAllAccount(params); //params coulbe pe page=1 or other url parameters
if (results) {
normalizePagination(results, setAccounts, setPages); //function which normalize pagination
}
normalizePagination(results, setAccounts, setPages);
  1. results is data from backend, you're api calls should remove all unnecessary details and leaving paginated results or just plain list of data (array).
  2. setAccounts is not necessarirly needed to be called setAccounts, it could be any thing with stores your results array. The data to be displayed on screen.
  3. setPages this is a setter function and it sets values for the page number

We can wire all these thru useEffect to make it complete working pagination system. As below code snipets

const getAllAccounts = async (params?: string) => {
try {
setIsLoading(true);
let results = await api.pullAllAccount(params);
if (results) {
normalizePagination(results, setAccounts, setPages);
}
} catch (ex) {
console.log(ex);
setAccounts([]);
} finally {
setIsLoading(false);
}
};

useEffect(() => {
getAllAccounts(searchParams.toString() ? searchParams.toString() : "page=1");
}, [searchParams]);

Note: searchParams use from react-router-dom's useSearchParams hook this will rerender our page since our pagination is browser-conscious

The pagination on the footer will be displayed by Paginator component itself as below

<Paginator pages={pages} callback={progressPage} />

Thats it.

This progressPage comes from SearchUtils util function and imported as

//on top of your page
const { progressPage } = SearchUtils(searchParams, setSearchParams);