Sub topic 12
Choosing between @wire, imperative Apex, and Lightning Data Service
You now know three ways to get Salesforce data into a Lightning Web Component (LWC): wiring an Apex method, calling Apex imperatively, and using Lightning Data Service (LDS). This chapter gives you criteria for picking one. It assumes you can write a cacheable @AuraEnabled method, import it, and wire it to a property or function, as covered in earlier chapters.
The three options
Each option answers a different question about who decides when the data loads, and who writes the server code.
- Lightning Data Service is the platform layer behind
lightning-record-form,lightning-record-edit-form, and thelightning/uiRecordApimodule. You name a record and its fields. The platform loads the data, checks object and field permissions, and caches the record. - Wired Apex runs a method you wrote and provisions the result to your component. The platform decides when to call it, based on your reactive parameters.
- Imperative Apex runs the same kind of method when your code calls it. You decide when, and you handle the promise.
| Question | LDS | Wired Apex | Imperative Apex |
|---|---|---|---|
| Who writes server code? | Nobody | You | You |
| Who triggers the call? | The platform | The platform, when parameters change | Your code |
| Can it change data? | Yes, through `createRecord`, `updateRecord`, `deleteRecord` | No, the method must be cacheable | Yes, with a non-cacheable method |
| Query shape | One record, or a related list, through the UI API | Any SOQL or SOSL you write | Any SOQL, SOSL, or DML you write |
| Permissions | Object access and field-level security enforced for you | You enforce them in Apex | You enforce them in Apex |
| Cache | Shared across components, kept in sync | Client-side cache for cacheable methods | A cacheable method can return cached results |
Start with LDS
Prefer LDS whenever your need fits it. You write no Apex and no tests for server code. Several components showing the same record share one cache entry, so an edit in one component updates the others. LDS also enforces object access and field-level security without any code from you.
This component shows an account name using getRecord:
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import ACCOUNT_NAME from '@salesforce/schema/Account.Name';
export default class AccountName extends LightningElement {
@api recordId;
@wire(getRecord, { recordId: '$recordId', fields: [ACCOUNT_NAME] })
account;
get name() {
return getFieldValue(this.account.data, ACCOUNT_NAME);
}
}Importing the field from @salesforce/schema gives you a compile-time check that the field exists. It also makes the dependency visible to deployment tools.
LDS stops being enough when you need something the UI API does not offer:
- A filtered or sorted list of records chosen by your own criteria.
- Aggregates, joins across unrelated objects, or SOSL search.
- Logic that must run on the server, such as callouts or multi-record transactions.
- A response shaped differently from the record fields.
Use wired Apex for custom reads
Choose a wire when the component displays data that your own query produces and the data should follow its inputs. The contact list in this tutorial is the standard case. The query filters by account, so LDS cannot express it directly.
A wire fits when all of these hold:
- The method only reads data, so it can be
cacheable=true. - The result depends on reactive values, such as
$recordId, and you want it to reload when they change. - You want the platform to manage the call timing and the
dataanderrorprovisioning.
Wires have limits. The call starts when the component connects and the parameters are defined, not when your code chooses. You cannot attach one to a button click. Cached results can also be stale until you call refreshApex.
Use imperative Apex for actions and control
Call Apex imperatively when your code must decide when the call happens, or when the method is not cacheable. Typical cases:
- Changing data. Any method that runs DML (
insert,update,delete) cannot be cacheable, so it cannot be wired. - User-triggered reads. A search box that queries only after the user presses Enter, or a "Load more" button.
- Sequenced work. One call depends on the result of another, or you need
async/awaitandtry/catcharound the whole flow. - Fresh data every time. You do not want a cached answer.
Here is a non-cacheable method that creates a contact. It runs with sharing and uses insert as user so object and field permissions apply:
public with sharing class ContactWriter {
@AuraEnabled
public static Contact createContact(Id accountId, String lastName, String email) {
Contact c = new Contact(AccountId = accountId, LastName = lastName, Email = email);
insert as user c;
return c;
}
}Combine them in one component
A real component often mixes a wire for reading with an imperative call for writing. After the write, the wired list is stale, so you refresh it. This component lists contacts with a wire and creates one imperatively:
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
import createContact from '@salesforce/apex/ContactWriter.createContact';
export default class ContactManager extends LightningElement {
@api recordId;
wiredResult;
rows;
lastName = '';
email = '';
errorMessage;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts(result) {
this.wiredResult = result;
if (result.data) {
this.rows = result.data;
this.errorMessage = undefined;
} else if (result.error) {
this.rows = undefined;
this.errorMessage = this.reduceError(result.error);
}
}
handleChange(event) {
this[event.target.dataset.field] = event.target.value;
}
async handleCreate() {
try {
await createContact({
accountId: this.recordId,
lastName: this.lastName,
email: this.email
});
this.errorMessage = undefined;
await refreshApex(this.wiredResult);
} catch (error) {
this.errorMessage = this.reduceError(error);
}
}
reduceError(error) {
return error.body ? error.body.message : error.message;
}
}The matching template wires the inputs to handleChange through data-field:
<template>
<lightning-input label="Last name" data-field="lastName" onchange={handleChange}></lightning-input>
<lightning-input label="Email" data-field="email" onchange={handleChange}></lightning-input>
<lightning-button label="Add contact" onclick={handleCreate}></lightning-button>
<p lwc:if={errorMessage}>{errorMessage}</p>
<ul>
<template for:each={rows} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>If the component only needed to add a contact, createRecord from lightning/uiRecordApi would do the same job with no Apex. Use the Apex version when the write needs custom logic, such as setting several related records in one transaction.
A decision path
Work through the questions in order. The first one that fits settles it.
Common mistakes
- Wiring a method that is not cacheable. A wire requires
cacheable=true. Without it the wire reports an error instead of data. If the method needs DML, call it imperatively. - Putting DML in a cacheable method. The platform rejects DML in cacheable methods, because cached reads must not change data. Split the method into one read and one write.
- Forgetting that writes leave wired data stale. After an imperative save, call
refreshApexon the stored wire result. If the data also lives in LDS, notify the LDS cache withnotifyRecordUpdateAvailablefromlightning/uiRecordApi. - Expecting an imperative call to a cacheable method to always hit the server. It can return cached data. When freshness matters, use a non-cacheable method, or call
refreshApexon a wire. - Writing Apex for something LDS already does. A single-record read with standard fields needs no Apex, and skipping it removes a permissions risk.
- Trusting the client for security. Whichever route you choose, Apex you write must enforce sharing and field-level security itself (
with sharingandWITH USER_MODEoras user). LDS does this for you, which is one more reason to prefer it.
Quick criteria
- Standard record data, edited or shown as-is: LDS.
- Custom read, driven by reactive values, no side effects: wired Apex.
- Any write, any call tied to a user action, or any call needing fresh data: imperative Apex.
- Mixed needs: LDS for the record, a wire for the custom list, imperative calls for actions, then refresh what the action made stale.
Exercise
A component shows a list of open cases for an account, filtered by status and sorted by priority, and reloads when the account changes. Which option do you choose, and what must be true of the Apex method?
Show answer
Use wired Apex. The query is custom, the call is a read, and it should reload when $recordId changes. The method must be @AuraEnabled(cacheable=true) and contain no DML. It should run with sharing and enforce field permissions, for example with WITH USER_MODE.
Exercise
A "Close case" button updates a case through a custom Apex method with business rules. The component also has a wired list of cases. Which call style do you use for the button, and what do you do after it succeeds?
Show answer
Call the method imperatively, because it runs DML and so cannot be cacheable or wired. After the promise resolves, call refreshApex on the stored result of the wired list so the list shows the change. Wrap the call in try/catch and display error.body.message.