Pagination with Lightning Components

Pagination isn't accomplished server-side in Lightning; but instead done by client-side code. See my gist for an example that loads up to 50,000 rows. If you need more than that, you simply need to load the data from the server in pieces, as demonstrated here; basically, just query X number of records, and if there's still more data to get, use the ID as a condition for the next query to get the next "page" of data. Lightning is fast enough that you should be sorting and paging client-side without resorting going back to the server all the time.


The Dreamhouse App has some code for server-side Pagination. The initial page load is faster than loading 1000+ records, but the first time you load the next / previous page it is slower. With action.setStorable(), subsequent visits to the pages are much faster. Like anything, there are trade-offs. For the full implementation, install the Dreamhouse app in a Developer org.

Here's my modified version of the Apex Class and an @AuraEnabled method that gets records using the PagedResult class.

public with sharing class PagedResult {
    @AuraEnabled
    public Integer pageSize { get; set; }

    @AuraEnabled
    public Integer page { get; set; }

    @AuraEnabled
    public Integer total { get; set; }

    @AuraEnabled
    public List<Object> results { get; set; }
}

then in your Apex Controller for your Lightning component you'd have

@AuraEnabled
public static PagedResult getPagedRecords(String sObjectName, String fieldNames, Decimal pageSize, Decimal pageNumber) {
    Integer pSize = (Integer)pageSize;
    Integer offset = ((Integer)pageNumber - 1) * pSize;
    PagedResult pr =  new PagedResult();
    String totalQuery = 'SELECT Id FROM ' + sObjectName;
    pr.pageSize = pSize;
    pr.page = (Integer) pageNumber;
    String query = 'SELECT ' + fieldNames + ' FROM ' + sObjectName;
    pr.total = Database.query(totalQuery).size();
    pr.results = Database.query(query + ' LIMIT :pSize OFFSET :offset');
    return pr;
}