Sub topic 12
Loading more rows on scroll
This chapter shows how to load records in pages as the user scrolls a lightning-datatable, instead of fetching everything at once. It assumes you can already render a table from Apex, as in the earlier chapters on data, columns, key-field, and loading records. You should also be comfortable calling an Apex method imperatively and updating a reactive class field in LWC.
Why load rows in pages
A single query with LIMIT 50 is easy, but real lists are larger. Loading thousands of rows up front slows the first render and wastes server time on rows nobody scrolls to. Infinite loading starts with a small first page. The table then asks for more when the user scrolls near the bottom.
The table does not fetch anything itself. It tells your component that the user is near the end, and your component decides what to fetch and how to add it to data.
The attributes involved
Four attributes control infinite loading.
| Attribute | Type | Purpose |
|---|---|---|
| `enable-infinite-loading` | boolean | Turns on the `loadmore` event. Set it to `false` when no rows remain. |
| `load-more-offset` | number | Distance in pixels from the bottom at which `loadmore` fires. The default is 20. |
| `is-loading` | boolean | Shows a spinner at the bottom of the table while you fetch. |
| `onloadmore` | event handler | Runs when the user scrolls within `load-more-offset` of the bottom. |
The event carries no useful detail. It means "the user is near the end". What to load next is up to you.
The flow
The sequence below shows one scroll-triggered load.
Apex: a pageable query
The wired getContacts method from earlier chapters has no parameters, so it always returns the same first page. For paging you need a method that accepts a page size and a starting position. This version uses OFFSET.
public with sharing class ContactPageController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContactPage(Integer pageSize, Integer offset) {
return [
SELECT Id, Name, Email, Phone, Birthdate
FROM Contact
WITH USER_MODE
ORDER BY Name, Id
LIMIT :pageSize
OFFSET :offset
];
}
}Two details matter here.
- Stable ordering.
ORDER BY Name, IdaddsIdas a tiebreaker. Without it, two contacts with the same name can swap places between queries. That produces duplicate rows or skipped rows across pages. - Imperative calls. A
cacheable=truemethod can be called imperatively, as well as wired. Wire adapters are a poor fit for paging because eachloadmorecall needs fresh parameters at a moment you choose.
The component
The component keeps the loaded rows in data and the next starting position in offset. It uses two flags: isLoading drives the spinner, and enableInfiniteLoading switches the event off when rows run out.
import { LightningElement } from 'lwc';
import getContactPage from '@salesforce/apex/ContactPageController.getContactPage';
const PAGE_SIZE = 50;
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text' },
{ label: 'Email', fieldName: 'Email', type: 'email' },
{ label: 'Phone', fieldName: 'Phone', type: 'phone' },
{ label: 'Birthdate', fieldName: 'Birthdate', type: 'date-local' }
];
export default class ContactInfiniteTable extends LightningElement {
columns = COLUMNS;
data = [];
error;
offset = 0;
isLoading = false;
enableInfiniteLoading = true;
connectedCallback() {
this.loadPage();
}
handleLoadMore() {
this.loadPage();
}
async loadPage() {
if (this.isLoading) {
return;
}
this.isLoading = true;
try {
const rows = await getContactPage({
pageSize: PAGE_SIZE,
offset: this.offset
});
this.data = [...this.data, ...rows];
this.offset += rows.length;
this.error = undefined;
if (rows.length < PAGE_SIZE) {
this.enableInfiniteLoading = false;
}
} catch (e) {
this.error = e;
this.enableInfiniteLoading = false;
} finally {
this.isLoading = false;
}
}
get errorMessage() {
return this.error?.body?.message ?? 'Unknown error';
}
}The template wraps the table in a fixed-height container and binds the four attributes.
<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<div style="height: 320px">
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
hide-checkbox-column
enable-infinite-loading={enableInfiniteLoading}
load-more-offset="30"
is-loading={isLoading}
onloadmore={handleLoadMore}>
</lightning-datatable>
</div>
<template lwc:if={error}>
<p class="slds-p-around_small slds-text-color_error">{errorMessage}</p>
</template>
</lightning-card>
</template>What each piece does
The fixed-height container
The table only scrolls internally when its parent has a bounded height. Without the height: 320px wrapper, the table grows to fit every row. The page scrolls instead of the table, and loadmore never fires. Use a fixed height, or a flex or viewport-based height.
The guard at the top of `loadPage`
loadmore can fire again before the previous call finishes, for example when the user keeps scrolling. Checking isLoading first prevents two overlapping calls from requesting the same offset. Overlapping calls are the usual cause of duplicate rows, which make the table fail on non-unique key-field values.
Appending with a new array
The code assigns this.data = [...this.data, ...rows] and does not call this.data.push(...). LWC re-renders when a field is reassigned. Mutating the array in place may not refresh the table, and in other situations the array may be read-only (wired data is always read-only). Building a new array works in every case.
The end-of-data check
The code treats a page shorter than PAGE_SIZE as the last page and sets enableInfiniteLoading to false. If the total is an exact multiple of the page size, the component makes one extra call that returns zero rows. Then the length check ends loading. That costs one wasted query. If you cannot accept that, return a total count with the first page and compare it to data.length.
The first page must fill the container
The loadmore event fires as the user scrolls. If the first page is too short to fill the visible area, there may be nothing to scroll, and the user cannot reach later pages. Choose a page size that fills the container with room to spare. With 50 rows in a 320 px container this holds comfortably.
Common errors
- Duplicate key-field warnings. Usually caused by overlapping loads, an unstable
ORDER BY, or reusing anoffsetafter a failed call. Keep theisLoadingguard and order by a unique field. - The event never fires. Check that
enable-infinite-loadingistrue, the container has a bounded height, and the loaded rows exceed the visible area. - The spinner stays on.
isLoadingwas never reset after an error. Put the reset infinally, as shown. - The event fires forever after the data ends.
enableInfiniteLoadingwas never set tofalse. The table keeps asking for rows that do not exist. - Records past 2,000. Apex limits
OFFSETto 2,000 rows. A request beyond that raises an error.
Interaction with other features
Sorting
The client-side sort from the sorting chapter only sorts rows already loaded. If the user sorts by Name after two pages, the next page is appended at the bottom, unsorted relative to the rest. There are two reasonable fixes:
- Re-run the sort over the combined array after each append. This works for small totals, but the order is still only correct among loaded rows.
- Sort on the server. When the sort changes, send the field and direction to Apex, clear
data, resetoffsetto 0, setenableInfiniteLoadingback totrue, and load the first page again.
Option 2 is correct for large lists, because the server holds the full set.
Selection and drafts
Selected rows are tracked by key-field value, so appending rows does not clear the selection. If you reset data to reload from the start, selection and draft values for rows that no longer exist can be left behind. Clear them when you reset.
Refreshing
refreshApex applies to wired results, so it does not work here. To refresh the list, reset data, offset, and enableInfiniteLoading, then call loadPage() again. Because the method is cacheable, an imperative call can return a cached result. If users must see just-saved changes, either remove cacheable=true (and call the method imperatively only) or add a changing parameter to the call.
Summary of the pattern
- Wrap the table in a fixed-height container.
- Load the first page in
connectedCallback. - Set
enable-infinite-loading,is-loading, andonloadmoreon the table. - Guard against overlapping calls with
isLoading. - Append with a new array, and advance
offsetby the number of rows received. - Turn off
enable-infinite-loadingon the last page or on error.
Exercise
Your table loads 50 contacts per page. A user scrolls quickly and sees the same contact twice, and the console reports duplicate key-field values. Name two causes in the component or query, and the fix for each.
Show answer
First, overlapping loads. If loadmore fires again before the previous Apex call returns, both calls use the same offset and return the same rows. Fix it by returning early from loadPage while isLoading is true. Second, an unstable ORDER BY. If the query orders only by a non-unique field like Name, rows with equal names can change position between queries and appear on two pages. Fix it by adding Id as a tiebreaker: ORDER BY Name, Id.
Exercise
The user has loaded 150 rows and the final Apex call returns 20 rows with a page size of 50. What should the component do with enableInfiniteLoading, and why?
Show answer
Set it to false. A page shorter than the page size means no more rows exist. If it stays true, the table keeps firing loadmore near the bottom, and each event triggers a query that returns nothing.