Sub topic 12
Loading more rows on scroll
This chapter assumes you can wire or call an Apex method from a Lightning Web Component and that you know how data, columns, and key-field work on lightning-datatable. Infinite loading lets the table fetch rows in pages as the user scrolls, so the first render stays fast.
How infinite loading works
Three attributes control it:
enable-infinite-loadingturns on theloadmoreevent.onloadmorenames your handler. The table fires the event when the user scrolls withinload-more-offsetpixels of the bottom. The default is 20.is-loadingshows a spinner while you fetch.
The table never fetches anything itself. Your component must append the new rows to data and tell the table when to stop.
The Apex method
Wired data cannot be extended, so load pages imperatively. A cacheable method can be called imperatively.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContactsPage(Integer pageSize, Integer rowOffset) {
return [
SELECT Id, Name, Email, Phone, Birthdate
FROM Contact
WITH USER_MODE
ORDER BY Name, Id
LIMIT :pageSize
OFFSET :rowOffset
];
}
}The extra Id in ORDER BY keeps the order stable between pages when names repeat.
The component
import { LightningElement } from 'lwc';
import getContactsPage from '@salesforce/apex/ContactController.getContactsPage';
const PAGE_SIZE = 50;
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'Email', fieldName: 'Email', type: 'email' },
{ label: 'Phone', fieldName: 'Phone', type: 'phone' }
];
export default class ContactTable extends LightningElement {
columns = COLUMNS;
data = [];
error;
isLoading = false;
enableInfiniteLoading = true;
connectedCallback() {
this.loadRows();
}
handleLoadMore() {
this.loadRows();
}
async loadRows() {
if (this.isLoading) {
return;
}
this.isLoading = true;
try {
const rows = await getContactsPage({
pageSize: PAGE_SIZE,
rowOffset: this.data.length
});
this.data = [...this.data, ...rows];
if (rows.length < PAGE_SIZE) {
this.enableInfiniteLoading = false;
}
} catch (e) {
this.error = e;
this.enableInfiniteLoading = false;
} finally {
this.isLoading = false;
}
}
}The isLoading guard prevents a second request while one is running. this.data.length serves as the offset because every page is appended. A short page means no more records exist, so the handler turns off enableInfiniteLoading.
The template
<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<div style="height: 300px;">
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
hide-checkbox-column
enable-infinite-loading={enableInfiniteLoading}
is-loading={isLoading}
onloadmore={handleLoadMore}>
</lightning-datatable>
</div>
</lightning-card>
</template>The wrapper div needs a fixed height. Without it the table grows to fit all its rows, nothing scrolls, and loadmore never fires.
Common errors
- No scrolling, no event. The first page is too short to fill the container, or the container has no height. Make the first page larger than the visible area.
- Duplicate rows. The code replaced the offset logic or fired two loads at once. Keep the
isLoadingguard. - Loading stops at 2,000 rows. SOQL
OFFSEThas a maximum of 2,000. For larger sets, page by a keyset, such asName > :lastName. - Sorting looks wrong. A client-side sort only orders the rows loaded so far. Pass the sort field and direction to Apex and reset
dataif you need a true global sort.
Exercise
Your table loads 50 contacts per page, and the last page returns 20 rows. What should the handler do, and why?
Show answer
It should append the 20 rows and set enableInfiniteLoading to false. A page shorter than PAGE_SIZE means no records remain, so the table must stop firing loadmore and calling Apex for pages that do not exist.