Sub topic 9
Paging with cursors
This chapter assumes you can write a basic @wire(graphql) query, read edges and node in the result, and pass reactive variables from a getter. If any of that is unfamiliar, review the earlier chapters on the adapter and on reactive variables first.
Why cursors instead of offsets
A query that returns every account in an org is slow and wasteful, and a component rarely needs all of them at once. Paging splits a large result set into small chunks that the component requests one at a time.
Many APIs page with an offset, such as "skip 20 rows, give me 10". The uiapi GraphQL schema uses cursors instead. A cursor is an opaque string that marks a position in the result set. You ask for the records that come after a given cursor.
Treat a cursor as a black box. Do not decode it, build it yourself, or store it for later sessions. The only valid source of a cursor is a previous response from the same query.
The pieces of a paged query
Paging uses two arguments on the object field and one extra selection.
| Piece | Where | Purpose |
|---|---|---|
| `first` | Argument on the object field | How many records to return in this page. |
| `after` | Argument on the object field | The cursor to start after. Leave it out or pass `null` for the first page. |
| `pageInfo` | Selection beside `edges` | Tells you whether more records exist and gives the cursor for the last record on this page. |
Inside pageInfo, the two fields you use most are:
hasNextPageistruewhen more records exist after this page.endCursoris the cursor of the last record in this page. You pass it asafterto get the next page.
Some connections also expose hasPreviousPage and startCursor. This chapter does not rely on them, because backward paging is easy to build with a history of cursors you already have (see below).
You can also select totalCount beside edges to learn how many records match the query. It is handy for a "Showing 5 of 240" label, but it can add cost on large data sets. Select it only if the UI needs it.
How a page request flows
The sequence below shows one "Next" click. The component never calculates a position. It hands back the cursor it received.
The rerun happens because after is part of the reactive variables object. When the getter returns new values, the wire service sees a changed parameter and provisions the adapter again. This is the same mechanism you used for reactive variables in the previous chapters.
A forward-only pager
This component shows five accounts at a time and has a Next button. The query declares $first and $after as variables, and pageInfo sits at the same level as edges.
import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/uiGraphQLApi';
export default class AccountPager extends LightningElement {
pageSize = 5;
after = null;
accounts = [];
pageInfo = { hasNextPage: false, endCursor: null };
@wire(graphql, {
query: gql`
query pagedAccounts($first: Int, $after: String) {
uiapi {
query {
Account(first: $first, after: $after, orderBy: { Name: { order: ASC } }) {
edges { node { Id Name { value } } }
pageInfo { hasNextPage endCursor }
}
}
}
}
`,
variables: '$variables'
})
wiredPage({ data }) {
if (data) {
const result = data.uiapi.query.Account;
this.accounts = result.edges.map(({ node }) => ({ id: node.Id, name: node.Name.value }));
this.pageInfo = result.pageInfo;
}
}
get variables() {
return { first: this.pageSize, after: this.after };
}
handleNext() {
if (this.pageInfo.hasNextPage) {
this.after = this.pageInfo.endCursor;
}
}
}Three details matter here:
- The
orderByis explicit. Cursor paging only makes sense over a stable order. Without one, you cannot reason about which records land on which page. handleNextcheckshasNextPagebefore moving. On the last page,endCursorstill has a value, and asking for records after it returns an empty page.- The handler copies
pageInfofrom the result. The component readsendCursorfrom the most recent response and never invents one.
Adding a Previous button
Cursors point forward, so going back needs a different approach. Remember the cursor that started each page you visited. To go back, step to the earlier entry in that list.
The first page starts with after = null. After clicking Next, you add the endCursor of page 1, which starts page 2. The list grows by one cursor per page visited.
import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/uiGraphQLApi';
export default class AccountPagerWithBack extends LightningElement {
pageSize = 5;
startCursors = [null];
pageNumber = 0;
accounts = [];
pageInfo = { hasNextPage: false, endCursor: null };
@wire(graphql, {
query: gql`
query pagedAccounts($first: Int, $after: String) {
uiapi {
query {
Account(first: $first, after: $after, orderBy: { Name: { order: ASC } }) {
edges { node { Id Name { value } } }
pageInfo { hasNextPage endCursor }
}
}
}
}
`,
variables: '$variables'
})
wiredPage({ data }) {
if (data) {
const result = data.uiapi.query.Account;
this.accounts = result.edges.map(({ node }) => ({ id: node.Id, name: node.Name.value }));
this.pageInfo = result.pageInfo;
}
}
get variables() {
return { first: this.pageSize, after: this.startCursors[this.pageNumber] };
}
get isFirstPage() {
return this.pageNumber === 0;
}
get isLastPage() {
return !this.pageInfo.hasNextPage;
}
get label() {
return `Page ${this.pageNumber + 1}`;
}
handleNext() {
if (!this.pageInfo.hasNextPage) {
return;
}
const next = this.pageNumber + 1;
if (this.startCursors.length === next) {
this.startCursors = [...this.startCursors, this.pageInfo.endCursor];
}
this.pageNumber = next;
}
handlePrevious() {
if (this.pageNumber > 0) {
this.pageNumber -= 1;
}
}
}The matching template disables the buttons at the ends:
<template>
<lightning-card title="Accounts" icon-name="standard:account">
<ul class="slds-p-around_medium">
<template for:each={accounts} for:item="account">
<li key={account.id}>{account.name}</li>
</template>
</ul>
<div class="slds-p-around_medium">
<lightning-button label="Previous" onclick={handlePrevious} disabled={isFirstPage}></lightning-button>
<span class="slds-p-horizontal_small">{label}</span>
<lightning-button label="Next" onclick={handleNext} disabled={isLastPage}></lightning-button>
</div>
</lightning-card>
</template>The component replaces startCursors with a new array instead of calling push. That keeps the change visible to LWC's reactivity, and it avoids surprises if you later pass the array to a child component.
Resetting when the query changes
A cursor belongs to one specific query. If the user changes a filter, the sort order, or the page size, the saved cursors no longer mean anything. Reusing them can return the wrong records or an error.
Whenever an input that shapes the result changes, go back to the start:
handleSizeChange(event) {
this.pageSize = Number(event.detail.value);
this.startCursors = [null];
this.pageNumber = 0;
}Apply the same reset to any handler that changes a where value or a sort direction.
"Load more" instead of pages
Some interfaces append records to a growing list instead of replacing the page. The query stays the same, but the component accumulates results. Because the wire runs again with each new after, you append inside the handler:
wiredPage({ data }) {
if (data) {
const result = data.uiapi.query.Account;
const incoming = result.edges.map(({ node }) => ({ id: node.Id, name: node.Name.value }));
this.accounts = this.after ? [...this.accounts, ...incoming] : incoming;
this.pageInfo = result.pageInfo;
}
}The this.after ? ... : incoming check replaces the list on the first request and appends on later ones. If the user changes a filter, set after back to null and the list restarts. Be aware that the wire can also emit again after a refresh, which would append duplicates. If you combine "load more" with refreshing, deduplicate by id or reset the list before refreshing.
Edge cases to plan for
- Empty results.
edgesis an empty array andhasNextPageisfalse. Your template should handle an empty list. - Data changes between requests. Records can be created or deleted while the user pages. A page may show a record you already saw, or miss one. Cursor paging reduces this problem compared with offsets, but it cannot remove it.
- Exact page boundary. If the total is a multiple of the page size, the last full page still reports
hasNextPage: false. Trust the flag, not a count of rows. - Stale cursors. Do not keep cursors in local storage or send them between users. Request the first page again when a session starts.
- Page size. Smaller pages respond faster and use less memory. Larger pages mean fewer round trips. Pick a size that matches what the screen shows, and stay far below the 200-record limit.
Summary
- Page with
firstandafter, and selectpageInfo { hasNextPage endCursor }. - Put
afterandfirstin the reactivevariablesso a change reruns the query. - Always use an explicit
orderByso pages are predictable. - Build Previous by keeping the list of cursors that started each page.
- Reset cursor state whenever
where,orderBy, orfirstchanges.
Exercise
A user is on page 3 of an account list sorted by name. They type a search term, and your handler updates the where variable but leaves after unchanged. The list now shows a few records or none. Why does this happen, and what should the handler also do?
Show answer
The after cursor was produced by the earlier query, without the search filter, so it marks a position that has no valid meaning in the filtered result set. The server starts after that position in the new result set, which skips records or returns an empty page. The handler should reset the paging state at the same time as it changes where: set after to null (or, in the history version, set startCursors = [null] and pageNumber = 0) so the new query starts on its first page.
Exercise
In the Previous/Next component, why does handleNext only add pageInfo.endCursor to startCursors when startCursors.length === next?
Show answer
If the user already went forward and then back, the cursor for the next page is already stored in startCursors. Pushing it again would add a duplicate, which shifts every later index and breaks the page numbering. The length check adds a cursor only the first time the user reaches a new page.