Sub topic 7
Getting data into a component
This chapter assumes you know the basic structure of a Lightning web component (template, JavaScript class, meta file), JavaScript modules and decorators, and basic Apex and SOQL. It also assumes you can deploy with the Salesforce CLI.
A component on an Experience Cloud site gets data in one of three ways. It can use a wire adapter, which provisions data reactively. It can call an Apex method imperatively, in response to an event. Or it can receive values from the page editor or a parent component. This chapter covers the first two, because they are where most errors happen.
The two patterns
| Pattern | When it runs | Cache | Typical use |
|---|---|---|---|
| `@wire` | When the component connects, and again when a reactive parameter changes | Client-side, if the method is `cacheable=true` | Data shown on load |
| Imperative call | When your code calls it | None by default | Button clicks, saves, deletes, or queries that must be fresh |
Wire is the default choice for reading data. Use an imperative call when the action has side effects or when you decide when it runs.
Wiring an Apex method
The component below reads maxRows from the page editor. It wires the Apex method getMyCases and passes maxRows as a parameter.
import { LightningElement, api, wire } from 'lwc';
import isGuest from '@salesforce/user/isGuest';
import getMyCases from '@salesforce/apex/CaseListController.getMyCases';
export default class CaseList extends LightningElement {
@api maxRows = 5;
isGuest = isGuest;
@wire(getMyCases, { maxRows: '$maxRows' })
cases;
get hasCases() {
return Boolean(this.cases && this.cases.data && this.cases.data.length);
}
}Three details matter here.
- The
$prefix in'$maxRows'makes the parameter reactive. The runtime looks upthis.maxRowsand re-invokes the method when the value changes. Without the$, the string"maxRows"would be sent as a literal. - The wire adapter is only invoked once every reactive parameter is defined. If
this.maxRowsisundefined, the adapter waits. This is useful for chaining, and a common cause of "my wire never fires" bugs. - The result property
casesholds an object withdataanderror. Before the first response, both areundefined.
The Apex side must be annotated so the wire service can call it:
public with sharing class CaseListController {
@AuraEnabled(cacheable=true)
public static List<Case> getMyCases(Integer maxRows) {
return [
SELECT Id, CaseNumber, Subject, Status
FROM Case
WITH USER_MODE
ORDER BY CreatedDate DESC
LIMIT :maxRows
];
}
}cacheable=true is required for wiring. It also means the method must not perform DML (inserts, updates, deletes). WITH USER_MODE enforces the site user's object, field, and record access, which Chapter 9 covers in depth.
Rendering the result
The template handles three states: a guest visitor, a list of records, and no records.
<template>
<template lwc:if={isGuest}>
<p>Log in to see your cases.</p>
</template>
<template lwc:elseif={hasCases}>
<ul>
<template for:each={cases.data} for:item="c">
<li key={c.Id}>{c.CaseNumber}: {c.Subject}</li>
</template>
</ul>
</template>
<template lwc:else>
<p>No cases found.</p>
</template>
</template>Each item in for:each needs a key, and the key must be unique within the list. The record Id is the natural choice.
This template has a gap. When the wire returns an error, cases.data is undefined, so the user sees "No cases found". That message is wrong, because the request failed. The next section shows how to separate the two.
Handling loading and errors
Wire results give you three states: not yet loaded, loaded, and failed. Use a function instead of a property when you need to react to them.
import { LightningElement, api, wire } from 'lwc';
import getMyCases from '@salesforce/apex/CaseListController.getMyCases';
export default class CaseListSafe extends LightningElement {
@api maxRows = 5;
rows = [];
errorMessage;
loaded = false;
@wire(getMyCases, { maxRows: '$maxRows' })
wiredCases({ data, error }) {
if (data) {
this.rows = data;
this.errorMessage = undefined;
this.loaded = true;
} else if (error) {
this.rows = [];
this.errorMessage = error.body ? error.body.message : error.message;
this.loaded = true;
}
}
get isEmpty() {
return this.loaded && !this.errorMessage && this.rows.length === 0;
}
}The function is called with the same { data, error } shape each time a new value arrives. The loaded flag lets the template show a spinner until the first response, then the empty message only when the list is truly empty.
Apex errors arrive as an object whose body.message holds the text. Other errors, such as network failures, have a plain message. Handling both avoids showing "undefined".
Imperative calls
Use an imperative call when you control the timing. Import the method the same way, then call it as a function that returns a promise.
import { LightningElement } from 'lwc';
import getMyCases from '@salesforce/apex/CaseListController.getMyCases';
export default class CaseRefresh extends LightningElement {
rows = [];
errorMessage;
isLoading = false;
async handleRefresh() {
this.isLoading = true;
try {
this.rows = await getMyCases({ maxRows: 10 });
this.errorMessage = undefined;
} catch (error) {
this.errorMessage = error.body ? error.body.message : error.message;
} finally {
this.isLoading = false;
}
}
}Parameters go in a single object, and the property names must match the Apex parameter names exactly. The finally block clears the loading state whether the call succeeds or fails.
An imperative call to a cacheable=true method can still return data from the browser cache. If you need a fresh read after a change, either refresh the wire with refreshApex or call a method that is not cacheable.
Refreshing wired data
When a user changes data, the wired result is stale. refreshApex from @salesforce/apex asks the wire service to re-fetch. It needs the whole value provisioned by the wire, not only its data.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getMyCases from '@salesforce/apex/CaseListController.getMyCases';
export default class CaseListRefreshable extends LightningElement {
@api maxRows = 5;
wiredResult;
rows = [];
@wire(getMyCases, { maxRows: '$maxRows' })
wiredCases(result) {
this.wiredResult = result;
if (result.data) {
this.rows = result.data;
}
}
handleRefresh() {
return refreshApex(this.wiredResult);
}
}Storing result (not result.data) is the step people miss. refreshApex uses it to identify which wire to refresh.
Data flow overview
Edge cases
- Mutating wire data. The
dataobject is read-only. Copy it before sorting or editing, for example[...data]ordata.map(...). - Guest users. A guest has no case records of their own. The component hides the list, but the wire still runs and returns nothing useful. To avoid the call entirely, make a reactive parameter
undefinedwhile the visitor is a guest. - Apex class access. Each profile, including the guest profile, needs access to the Apex class. A missing grant produces an error at call time, not at deployment.
- Runtime differences. Both Aura and LWR sites support
@wirewith Apex. Check the supported imports for your runtime before using otherlightning/ui*Apiadapters, because support varies. - Null parameters. An Apex
Integerparameter that arrives asnullcausesLIMIT :maxRowsto fail. Validate it in Apex or set a default in the component.
Choosing a pattern
- Does the data load when the component appears, and is it read-only? Use
@wire. - Does the user trigger it, or does it change data? Use an imperative call.
- Do you need the result to refresh after a change? Keep the wired result and call
refreshApex. - Do you need to show an error or loading state? Use a wired function, not a property.
Exercise
A component uses @wire(getMyCases, { maxRows: 'maxRows' }). It never receives the value set in the page editor, and the Apex method gets the text "maxRows". What is wrong, and how do you fix it?
Show answer
The parameter is missing the $ prefix, so it is passed as a literal string instead of a reactive reference to this.maxRows. Change it to { maxRows: '$maxRows' }. The wire service then reads the property and calls the method again when the value changes.
Exercise
You wire an Apex method to a property named cases, and a user creates a new case through a separate component. The list does not update. What do you need to change?
Show answer
Wire the method to a function that stores the whole result, for example this.wiredResult = result, and call refreshApex(this.wiredResult) after the case is created. Passing only result.data to refreshApex does not work, because it needs the value provisioned by the wire service.