Sub topic 1
Exposing Apex to LWC with `@AuraEnabled(cacheable=true)`
Prerequisites
This chapter assumes basic JavaScript, ES modules, Lightning Web Component structure, Apex, and SOQL. You also need a Salesforce org or scratch org where you can deploy code.
Exposing Apex to LWC with `@AuraEnabled(cacheable=true)`
An Apex method is callable from an LWC when it is public or global, static, and annotated with @AuraEnabled. A method used with @wire must also use cacheable=true. This tells Salesforce that the method only reads data and that its result can be stored in a client-side cache.
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
];
}
}The method performs no data changes. It queries contacts and returns a list. with sharing applies the caller's record-sharing rules. WITH USER_MODE enforces the caller's object and field permissions for this query.
Importing the Apex Method into Your Component
Import the method from the @salesforce/apex module. The import name is a JavaScript reference to the Apex method, not a URL.
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 parameter name, accountId, must match the Apex method parameter. The $ before recordId makes the parameter reactive. When recordId changes, the wire service provisions the method again.
How `@wire` Provisions Data
@wire is a framework service that calls an Apex method and supplies its result to the component. When wiring to a property, Salesforce provides an object with data and error fields.
<template>
<template lwc:if={contacts.data}>
<ul>
<template for:each={contacts.data} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</template>
<template lwc:elseif={contacts.error}>
<p>Could not load contacts.</p>
</template>
</template>The component can render contacts.data when the request succeeds and inspect contacts.error when it fails. The wire service may first provide no value, so the template must handle both states.
Exercise
Why must an Apex method used with @wire be marked cacheable=true?
Show answer
Because wired methods must be read-only so Salesforce can safely cache and provision their results.