Sub topic 6
Loading records from Apex
This chapter covers how records get from the database into the data attribute of lightning-datatable. It assumes you can write a basic Lightning Web Component and read JavaScript destructuring. It also assumes you have called an Apex method from a component before. The earlier chapters on key-field and column definitions apply here without change.
The working model
lightning-datatable does not fetch anything. It renders whatever array you assign to data, using the columns array to decide which fields to show. Loading records is your component's job. Your component must also decide what the user sees while the call is running, when it returns nothing, and when it fails.
Three things have to line up:
- Each column's
fieldNamemust match a field name in the returned objects. - Every row must include the field named in
key-field, usuallyId. - The Apex query must select every field that a column uses.
If the query leaves out a field, the cell is blank. The table raises no error.
The Apex method
The method below returns the Contact records the table will show.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts() {
return [
SELECT Id, Name, Email, Phone, Birthdate
FROM Contact
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}Each part of this method has a reason:
@AuraEnabled(cacheable=true)makes the method callable from a component. It also allows@wireand client-side caching. A cacheable method must not change data.WITH USER_MODEenforces the running user's field-level security and sharing rules. A user who cannot readPhonegets an exception instead of silently receiving a partial result.ORDER BYgives a stable default order. Without it, the row order is not guaranteed.LIMIT 50keeps the payload small. A table that tries to hold thousands of rows is slow to render. Later chapters cover paging with infinite loading.
Wiring the method to the table
The next class wires the method and stores the result. It also tracks a loading flag so the table can show a spinner.
import { LightningElement, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
const COLUMNS = [
{ label: 'Name', fieldName: 'Name', type: 'text', sortable: true },
{ label: 'Email', fieldName: 'Email', type: 'email' },
{ label: 'Phone', fieldName: 'Phone', type: 'phone' },
{ label: 'Birthdate', fieldName: 'Birthdate', type: 'date-local' }
];
export default class ContactTable extends LightningElement {
columns = COLUMNS;
data = [];
error;
wiredResult;
isLoading = true;
@wire(getContacts)
wiredContacts(result) {
this.wiredResult = result;
const { data, error } = result;
if (data) {
this.data = data;
this.error = undefined;
this.isLoading = false;
} else if (error) {
this.error = error;
this.data = [];
this.isLoading = false;
}
}
get isEmpty() {
return !this.isLoading && this.data.length === 0;
}
get errorMessage() {
const e = this.error;
if (Array.isArray(e?.body)) {
return e.body.map((item) => item.message).join(', ');
}
return e?.body?.message ?? e?.message ?? 'Unknown error';
}
}The wired function receives one object. It holds either data or error, and both are undefined before the first response. That is why the handler checks each with if. It also saves the whole result object in wiredResult. Keep that object. refreshApex needs it later, and destructuring alone would lose it.
The errorMessage getter covers the three shapes you will meet. Apex errors arrive as error.body.message. Some errors carry an array in body. Network and client errors have only error.message.
The template: loading, empty, and error states
A table with no rows looks the same whether the data is still loading, the query returned nothing, or the call failed. Your template has to tell the user which one it is.
<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<template lwc:if={error}>
<p class="slds-p-around_medium slds-text-color_error">
{errorMessage}
</p>
</template>
<template lwc:else>
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
is-loading={isLoading}
hide-checkbox-column>
</lightning-datatable>
<template lwc:if={isEmpty}>
<p class="slds-p-around_medium">No contacts found.</p>
</template>
</template>
</lightning-card>
</template>The is-loading attribute shows a spinner over the table body. The empty message appears only after loading ends with zero rows. On an error, the table is replaced by the message.
Wire versus imperative calls
The wire service calls the method for you, and it caches the result. The alternative is to call the method yourself.
import { LightningElement } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactTableImperative extends LightningElement {
data = [];
error;
isLoading = true;
async connectedCallback() {
try {
this.data = await getContacts();
this.error = undefined;
} catch (e) {
this.error = e;
this.data = [];
} finally {
this.isLoading = false;
}
}
}| Aspect | `@wire` | Imperative call |
|---|---|---|
| When it runs | Automatically, and again when reactive parameters change | When your code calls it |
| Method must be cacheable | Yes | No |
| Refresh after a change | `refreshApex(wiredResult)` | Call the method again |
| Error shape | `result.error` | Rejected promise |
| Good for | Read-only display that follows parameters | Searches on a button click, saves, methods that change data |
Use @wire for the initial display. Use an imperative call when the load depends on a user action or when the method cannot be cacheable.
Refreshing after changes
A cacheable result can be stale. If a user edits a record elsewhere, the wire may serve the cached copy. After you change data from your own component, call refreshApex with the saved wired result:
import { refreshApex } from '@salesforce/apex';
async handleReload() {
this.isLoading = true;
await refreshApex(this.wiredResult);
this.isLoading = false;
}refreshApex re-runs the wire and invokes your wired function again with fresh data. You must pass the exact object the wire provided. Passing result.data does nothing useful. refreshApex works only with wired methods, not imperative ones.
Gotchas
Wired data is read-only
The array and its objects are frozen. Writing this.data[0].Name = 'x' fails, and this.data.sort(...) throws or does nothing. Copy first, as in [...this.data].sort(...). For nested edits, copy the row too: this.data.map((row) => ({ ...row })).
Relationship fields come back nested
A query such as SELECT Account.Name FROM Contact returns { Account: { Name: 'Acme' } }. A column with fieldName: 'Account.Name' will not read it. Flatten the rows before assigning them:
this.data = data.map((row) => ({
...row,
AccountName: row.Account?.Name
}));Then use fieldName: 'AccountName'. Rows without an account produce undefined, which renders as an empty cell.
Fields with no value are missing
Apex omits a field with a null value from the serialized object. A cell for it is blank, and row.Phone is undefined, not null. This matters in sort code, which is why the sort handler in a later chapter uses ?? ''.
A failing query hides the whole table
With WITH USER_MODE, one field the user cannot read causes the whole call to throw. This is the safe behavior, but your component then shows only the error. Test the component as a user with a restricted profile, not just as an administrator.
Throw readable errors
Uncaught exceptions reach the component as generic messages. Catch expected failures in Apex and rethrow them as AuraHandledException with a useful message, so error.body.message is something a user can act on.
Checking your work
When the table is blank, check in this order:
- Open the browser console and look for a rejected call or a wire error.
- Confirm
key-fieldnames a field that the query selects. - Confirm each
fieldNamematches the query's field API name, with the same capitalization. - Log
JSON.stringify(result.data[0])in the wired function to see the real row shape. - Confirm the user has access to the object and fields.
Exercise
A component wires getContacts and has the table sorted by Name. A user edits a contact in another tab, then clicks a Reload button in your component that calls refreshApex(this.wiredResult). The table still shows the old name. Name two likely causes in your component's code.
Show answer
First, wiredResult may hold the wrong thing. If the handler saved data instead of the whole result object, refreshApex has nothing to refresh. Second, the component may be calling the method imperatively as well as wiring it, or may have copied result.data into a separate array that the Reload code never reassigns. refreshApex only re-runs the wire, which calls your wired function again. If the wired function does not assign the new data to the property bound to the table, the display does not change. A third possible cause is that the stale value comes from a cacheable method whose cache has not been invalidated by the other tab's edit, which refreshApex bypasses for the current wire only when the original result object is passed.
Exercise
Add a Contact column that shows the parent account's name using SELECT Id, Name, Account.Name FROM Contact. What do you change in the wired function and in the columns array so the cell is filled, including for contacts with no account?
Show answer
In the wired function, flatten each row with this.data = data.map((row) => ({ ...row, AccountName: row.Account?.Name }));. In the columns array, add { label: 'Account', fieldName: 'AccountName' }. The optional chaining ?. returns undefined for contacts with no account, so the cell stays empty instead of throwing an error.