UBOS Community

Olha
Olha

Posted on • Updated on

Кастомна пагінація з базою даних PostreSQL

Бувають випадки , коли потрібна серверна пагінація для відображення даних у віджеті, який немає властивості Server Side Pagination. В таких випадках можна створити власну пагінацію. На прикладі розглянемо віджет Carousel, де потрібно буде відобразити 3 зображення на кожній сторінці. Дані отримуємо з бази PostreSQL.
Про Server Side Pagination читайте тут.

Крок 1. У зaпиті до бази даних обов'язково вказуємо limit та offset.

Limit - скільки об'єктів ми повертаємо. В даному випадку 3.
Offset - скільки нам потрібно пропустити.

Наприклад, якщо це дані для першої сторінки, показуємо 3 об'єкти і пропускаємо 0. Для другої сторінки показуємо 3 і пропускаємо 3 перших.

Для того, щоб вирахувати, скільки даних потрібно пропустити, потрібно передавати номер сторінки, на яку ми хочемо отримати дані. Номер сторінки - msg.payload.page - передаємо з UI Editor. Про це читайте далі.

Image description

let offset = msg.payload.page * 3 - 3
msg.payload = `SELECT * FROM gallery limit 3 offset 3`
return msg;

Enter fullscreen mode Exit fullscreen mode

Крок 2. Ствоюємо API, яка відправляє запит, щоб отримати дані та передає номер сторінки у query params. Номер сторінки зберігаємо у main store. API запускаємо на Page load.

Image description

Image description

Далі потрібно створити три функції у JSObject.

Image description

Image description

  • storePageValue - функція запускається при завантаженні сторінки та зберігає у значення page 1;
storePageValue: () =>{
   storeValue("page", 1)
}
Enter fullscreen mode Exit fullscreen mode
  • increment - збільшує значення pageна 1 та викликає API getImages;
increment: async () => {
   await storeValue('page', main.store.page + 1)
   await getImages.run()
}
Enter fullscreen mode Exit fullscreen mode
  • decrement - зменшує значення pageна 1 та викликає API getImages;
decrement: async () =>{
   await storeValue('page', main.store.page - 1)
   await getImages.run()
}
Enter fullscreen mode Exit fullscreen mode

Крок 3. Використовуємо віджети:

  • Text - його text {{main.store.page}}

Image description

  • IconButton - у властивості onClick запускаємо функцію increment з JsObject1

Image description

  • IconButton - у властивості onClick запускаємо функцію decrement з JsObject1 та у полі Disabled натискаємо на значок JS і пишемо {{main.store.page === 1}}.

Image description

  • Carousel (у нашому випадку це віджет каруселі, може бути будь-який інший, який необхідний у конкретній ситуації) - у Contents вказуємо нашу апі - {{getImages.data}}.

Image description

Результат:

Discussion (1)

Collapse
metareps profile image
montycraig@hotmail.com • Edited on

English:

Custom Pagination with PostreSQL Database

There are cases when server-side pagination is needed to display data in a widget that doesn't have built-in Server Side Pagination functionality. In such cases, you can create your own pagination. Let's consider an example with the Carousel widget, where we need to display 3 images per page. The data is fetched from a PostreSQL database.

Step 1: In the database query, specify the "limit" and "offset" parameters.

"Limit" determines how many objects we return. In this case, it's 3.
"Offset" determines how many objects we need to skip.
For example, if it's data for the first page, we show 3 objects and skip 0. For the second page, we show 3 objects and skip the first 3.

To calculate the number of data to skip, we need to pass the page number we want to retrieve the data for. The page number is passed as "msg.payload.page" from the UI Editor.

Example:

Step 3: Create three functions in the JSObject.

storePageValue: This function is triggered on page load and stores the value of the page as 1.
increment: This function increases the value of the page by 1 and calls the getImages API.
decrement: This function decreases the value of the page by 1 and calls the getImages API.

Step 4: Use the following widgets: