Server Pagination Example (Reqres)
Static content
This example demonstrates how to implement server-side pagination using an external API (reqres.in).
When “Server Pagination” is enabled in the widget configuration, the script receives page and pageElements parameters.
Function Explanation
- Page Parameters: The
pageandpageElementsarguments act as the current page number and the page size (limit), respectively. - API Request: The code constructs a request to
reqres.inpassingpageandper_pagequery parameters. - Callback: The function processes the response and sends the array of users to the widget via the
callback.
Code
// Main function executed by the Custom Table widget
// parameters: entityData, filters, page, pageElements, callback
// 1. Prepare Pagination Parameters
// Ensure we have defaults if arguments are missing (safeguard)
const currentPage = page || 1;
const perPage = pageElements || 5;
// 2. Construct URL with pagination params
// reqres.in uses 'page' (1-based) and 'per_page'
const url = `https://reqres.in/api/users?page=${currentPage}&per_page=${perPage}`;
try {
// 3. Fetch Data
const response = await http(url);
// 4. Extract Data
// reqres.in returns: { page: 1, per_page: 6, total: 12, total_pages: 2, data: [...] }
let users = [];
// Check various response wrappers as 'http' might auto-parse JSON
if (response && response.data && Array.isArray(response.data)) {
users = response.data;
} else if (response && response.json) {
const json = await response.json();
users = json.data || [];
} else if (response && Array.isArray(response)) {
users = response;
}
// 5. Format for Table
// Configured Columns hint: 'id', 'avatar', 'first_name', 'last_name'
const tableData = users.map(user => {
return {
id: user.id,
avatar: `<img src="${user.avatar}" style="width: 30px; border-radius: 50%;">`,
first_name: user.first_name,
last_name: user.last_name,
email: user.email
};
});
// 6. Return Data
// We return the array of items for the current page.
callback(tableData);
} catch (error) {
console.error("Error fetching paged data:", error);
callback([]);
}