Sub topic 3
What `cacheable=true` Means and When You Can Use It
Assume you know basic JavaScript Promises, LWC event handlers, Apex, SOQL, and Salesforce security concepts.
Read-Only Methods and Client Caching
@AuraEnabled(cacheable=true) marks an Apex method as read-only. Salesforce can cache its result on the client, which can reduce server calls. The method must not perform DML or other changes.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> searchContacts(String searchTerm) {
String key = '%' + searchTerm + '%';
return [
SELECT Id, Name, Email
FROM Contact
WHERE Name LIKE :key
WITH USER_MODE
ORDER BY Name
LIMIT 20
];
}
}Use cacheable=true for searches and other queries whose results can be reused briefly. Do not use it for methods that insert, update, delete, or otherwise change data.
Wire Service or Imperative Call
Use the wire service when data should load reactively from properties or parameters. The framework manages invocation and provides a standard refresh path.
Use an imperative call when the user controls when the request happens, such as clicking Search, submitting a form, or choosing an action.
flowchart TD
A[User action] --> B[Imperative Apex call]
C[Reactive parameter] --> D[Wire service]
B --> E[Update component state]
D --> ERefreshing Data After a Change
After an imperative update, call the read method again to obtain current data. If the data came from a wired call, retain the wire result and pass it to refreshApex. For records displayed through Lightning Data Service, use notifyRecordUpdateAvailable when appropriate.
Security and Call Efficiency
Use with sharing so record-sharing rules apply. Use WITH USER_MODE in SOQL and user-mode DML where supported, so object and field permissions are enforced. Also validate parameters in Apex.
Debounce text-search requests, avoid calling Apex on every keystroke, and skip calls when required input is empty. Limit returned rows and selected fields.
Testing an Imperative Call
Jest tests mock the imported Apex function. Resolve the mock with sample data, trigger the event, and assert both the arguments and rendered output.
searchContacts.mockResolvedValue([
{ Id: '003000000000001', Name: 'Ada Lovelace', Email: '[email protected]' }
]);Exercise
Should an Apex method that updates a Contact use cacheable=true?
Show answer
No. It changes data, so it must be a non-cacheable @AuraEnabled method.