Salesforce LWC: Pagination vs. Infinite Scroll vs. See more




The idea for the three display methods as a carrier can deliver items. We assume that a delivery person can deliver 100 articles. The problem that his truck supports only 20 items. So you have to make 5 trips to deliver them all. 



It's the same idea for LWC is split the data and display by batch. In our tutorial, we will see together how to display data with pagination, infinity scroll or see more button.

Backend: Apex

All display types share the same apex function. The principle of the function is to retrieve data with:
  • Well-defined number of lines (With Limit). In our example, we will use 20 rows.
  • Data recovery starting range (With Offset). This value is modified according to the request.

To start the implementation, we need two functions:
  1. Function to retrieve data (getAccountsList)
  2. Function to retrieve numbers from global data (getAccountNumber)
       
    public with sharing class AccountController {
    
        @AuraEnabled
        public static List getAccountsList(Integer offsetValue,Integer limitValue) {
            return [SELECT Id, Name, Phone, Type FROM Account LIMIT :limitValue OFFSET :offsetValue];
        }

        @AuraEnabled
        public static Integer getAccountNumber() {
            return ([SELECT Id FROM Account]).size();
        }
    }
       
 



Pagination




First step, we are going to create a component with name Pagination which contains the buttons for changing pages. The input values for this component are:
  • numberOfLine: Variable contains the total number of data
  • limitOfLine: Variable contains the number of data per call

Infinite Scroll

Infinity scroll is based on scrollable movement. If the scrollbar position in 85% of the total length, a call is made to add more data.


We used to trigger the user's scroll event.
       
    // onscroll Event
    onScroll(event) {

        var scrollRate = event.target.scrollTop / (event.target.scrollHeight - event.target.clientHeight )

        if(scrollRate > 0.85 && this.data.length < this.accountNumber && this.isAddNewData) {
            this.isAddNewData = false;
            this.offsetValue += 20;
            this.getAccountsList();
        }
    }
       
 


See more

the same pagination logic, but the call according to click on the See more button.
       
    displayData() {
        this.offsetValue += 10;
        this.getAccountsList();
    }

Conclusion

We looked at three methods for optimizing our data display on Salesforce. To see all the code, download the code from my GitHub here.

Reference

Commentaires