Sub topic 2
Read-only Apex Methods with `cacheable=true`
Assume you know basic Apex, SOQL, Lightning Web Components (LWC), and Salesforce record IDs. An @AuraEnabled method is an Apex method exposed to Lightning components. Add cacheable=true when the method only reads data and its result can be reused by the client.
Read-only methods with `cacheable=true`
A cacheable method must not perform DML or other state-changing work. Use it for queries that can safely return cached data.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}with sharing applies record-level sharing rules. WITH USER_MODE also enforces the running user's object and field permissions for this query.
| Method type | `cacheable=true` | Typical use |
|---|---|---|
| Read-only | Yes | Query records |
| Creates or updates data | No | Insert, update, or delete records |
Calling Apex declaratively with `@wire`
The @wire decorator connects an Apex method to a component property. A parameter beginning with $ is reactive. The method runs again when that component property changes.
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactList extends LightningElement {
@api recordId;
@wire(getContacts, { accountId: '$recordId' })
contacts;
}The contacts property contains either data or error. The template can render the appropriate state. Wired calls are a good fit for data that the component displays automatically.
Calling Apex imperatively
An imperative call is a direct JavaScript function call. It returns a promise, so use await or .then(). Use this style for button actions, conditional reads, and methods that perform DML.
import { LightningElement, api } from 'lwc';
import createContact from '@salesforce/apex/ContactController.createContact';
export default class ContactCreator extends LightningElement {
@api recordId;
async save(lastName) {
try {
const contact = await createContact({
lastName,
accountId: this.recordId
});
return contact;
} catch (error) {
console.error(error.body?.message ?? error.message);
throw error;
}
}
}The called Apex method must omit cacheable=true if it inserts, updates, or deletes records. Imperative calls can also invoke cacheable methods when the component needs to control exactly when a read occurs.
Exercise
Which call style should you choose for a read-only contact list that must reload when recordId changes?
Show answer
Use a cacheable Apex method with @wire and pass recordId as a reactive $recordId parameter.