Sub topic 6
Loading records from Apex
This chapter assumes you can write a basic Lightning Web Component (LWC), and that you know JavaScript destructuring and how to wire an Apex method. It also assumes you know Salesforce objects and fields. The goal is to get Contact records from the server into lightning-datatable, and to handle the empty and error cases.
The working model
The @wire decorator calls an Apex method and gives your component a result object with two properties, data and error. Exactly one of them is set once the call completes. The table needs neither Apex nor wire. It only renders the data array you pass in, so the loading code and the display code are separate concerns.
The Apex method must be @AuraEnabled(cacheable=true) to be wired. It must also select every field that a column's fieldName refers to, plus Id for the key-field.
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
];
}
}WITH USER_MODE enforces the running user's field and object permissions. LIMIT 50 keeps the first load small.
Wiring the method to the component
Wire to a function instead of a property. That lets you keep the whole result object, which refreshApex needs later, and lets you set your own state for each outcome.
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 hasRows() {
return this.data.length > 0;
}
get errorMessage() {
return this.error?.body?.message ?? 'The contacts could not be loaded.';
}
}Each branch resets the other state. Without that, an old error could stay on screen after a later successful refresh.
Handling the empty and error cases
The template has to cover four states: loading, error, empty, and data.
<template>
<lightning-card title="Contacts" icon-name="standard:contact">
<template lwc:if={isLoading}>
<lightning-spinner alternative-text="Loading"></lightning-spinner>
</template>
<template lwc:elseif={error}>
<p class="slds-p-around_medium slds-text-color_error">{errorMessage}</p>
</template>
<template lwc:elseif={hasRows}>
<lightning-datatable
key-field="Id"
data={data}
columns={columns}
hide-checkbox-column>
</lightning-datatable>
</template>
<template lwc:else>
<p class="slds-p-around_medium">No contacts found.</p>
</template>
</lightning-card>
</template>Common errors
| Symptom | Cause | Fix |
|---|---|---|
| The wire returns an error immediately | The Apex method is missing `cacheable=true` | Add it, or call the method imperatively |
| A column is blank | The field is not in the SOQL `SELECT` list, or `fieldName` is misspelled | Query the field and match the name exactly |
| Rows behave oddly or the console warns about keys | `Id` was not queried or `key-field` is wrong | Select `Id` and set `key-field="Id"` |
| A column for `Account.Name` is blank | `fieldName` does not read nested paths | Flatten the records into a new property before assigning `data` |
| Sorting throws an error on `data` | Wired data is read-only | Sort a copy, such as `[...this.data]` |
Exercise
The table renders, but the Email column is empty for every row. The column definition is { label: 'Email', fieldName: 'Email', type: 'email' }. What is the most likely cause, and where do you fix it?
Show answer
The Apex SOQL query does not select Email, so the field is missing from each record. Add Email to the SELECT list in getContacts. The column definition is correct.