Sub topic 13
Calling the same methods from Aura components
This chapter assumes you have read the earlier chapters on @AuraEnabled method rules, cacheable=true, wrapper classes, and error handling with AuraHandledException. You should also know basic Aura markup: aura:component, attributes, and the client-side controller and helper files.
Despite its name, @AuraEnabled is not specific to Aura. The annotation exposes a method to the Lightning component framework, and both Lightning Web Components (LWC) and Aura components use it. The Apex classes you wrote for LWC need no changes to serve Aura. Only the client-side calling code differs.
Why you might still call Apex from Aura
Many orgs have Aura components that predate LWC. You may need to extend one, share an Apex controller between old and new components, or migrate gradually. Aura components can contain LWC components, but not the other way around. A common migration path is to move the leaf components to LWC first and leave the Aura wrapper in place. Both layers can use the same controller class.
One Apex method, two ways to reach it
The following diagram shows how one Apex method serves both frameworks.
The following table maps each LWC idea to its Aura counterpart.
| Concern | LWC | Aura |
|---|---|---|
| Reference the method | `import getContacts from '@salesforce/apex/ContactController.getContacts'` | `controller="ContactController"` on the component, then `component.get("c.getContacts")` |
| Pass parameters | Object passed to the function or wire config | `action.setParams({ accountId: ... })` |
| Read the result | Promise result or `data` on the wire | `response.getReturnValue()` in a callback |
| Read errors | `error.body.message` | `response.getError()[0].message` |
| Declarative, reactive call | `@wire` | Not available |
| Refresh cached data | `refreshApex` | Enqueue the action again |
Aura has no wire service for Apex. Every Aura call is imperative: you build an action, set its parameters and callback, and enqueue it.
Declaring the controller
An Aura component names its Apex class in the controller attribute of aura:component. The framework then lets the component look up any @AuraEnabled static method in that class. A component can name only one Apex controller.
The markup below uses the ContactController class from earlier chapters. It adds a lastName attribute for the create example later in the chapter.
<aura:component controller="ContactController"
implements="flexipage:availableForRecordHome,force:hasRecordId">
<aura:attribute name="contacts" type="Contact[]" />
<aura:attribute name="lastName" type="String" default="" />
<aura:attribute name="errorMessage" type="String" default="" />
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<lightning:card title="Contacts" iconName="standard:contact">
<aura:if isTrue="{!not(empty(v.errorMessage))}">
<p class="slds-p-horizontal_small slds-text-color_error">{!v.errorMessage}</p>
</aura:if>
<aura:iteration items="{!v.contacts}" var="contact">
<p class="slds-p-horizontal_small">{!contact.Name}</p>
</aura:iteration>
<div class="slds-p-around_small">
<lightning:input label="Last name" value="{!v.lastName}" />
<lightning:button label="Create contact" onclick="{!c.handleCreate}" />
</div>
</lightning:card>
</aura:component>The force:hasRecordId interface gives the component a recordId attribute. Aura fills it in when the component sits on a record page, the same way @api recordId works in LWC.
Calling a read method
The client-side controller stays thin and the helper holds the logic. This is the convention in Aura code.
({
doInit: function (component, event, helper) {
helper.loadContacts(component);
},
handleCreate: function (component, event, helper) {
helper.createContact(component);
}
})The helper builds the action and enqueues it.
({
loadContacts: function (component) {
var action = component.get("c.getContacts");
action.setParams({ accountId: component.get("v.recordId") });
action.setCallback(this, function (response) {
var state = response.getState();
if (state === "SUCCESS") {
component.set("v.contacts", response.getReturnValue());
component.set("v.errorMessage", "");
} else if (state === "ERROR") {
component.set("v.errorMessage", this.extractMessage(response.getError()));
} else if (state === "INCOMPLETE") {
component.set("v.errorMessage", "No response from the server. Check your connection.");
}
});
$A.enqueueAction(action);
},
createContact: function (component) {
var action = component.get("c.createContact");
action.setParams({
lastName: component.get("v.lastName"),
accountId: component.get("v.recordId")
});
action.setCallback(this, function (response) {
if (response.getState() === "SUCCESS") {
component.set("v.lastName", "");
component.set("v.errorMessage", "");
this.loadContacts(component);
} else {
component.set("v.errorMessage", this.extractMessage(response.getError()));
}
});
$A.enqueueAction(action);
},
extractMessage: function (errors) {
if (errors && errors[0] && errors[0].message) {
return errors[0].message;
}
return "Unknown error";
}
})Several details in this code matter.
- The call returns an action, not data.
component.get("c.getContacts")returns a server action object. Nothing runs until$A.enqueueAction(action). - Parameter names must match Apex. The keys in
setParamsmust match the Apex parameter names exactly. In the example,accountIdandlastNamematch the signatures ofgetContactsandcreateContact. - The callback is asynchronous. Code after
$A.enqueueActionruns before the server responds, so read the result only inside the callback. setCallback(this, ...)sets the scope. In a helper, passingthislets the callback call other helper functions such asthis.extractMessage.- Three states need handling.
SUCCESSandERRORare the usual two.INCOMPLETEmeans the server could not be reached, for example when the user is offline. Skipping it leaves the user with a blank component and no message.
The write call and error messages
The createContact method from the earlier chapters throws AuraHandledException when a DmlException occurs. In Aura, that message arrives in the error array.
response.getError()returns an array of error objects.- For a thrown
AuraHandledException,errors[0].messageholds the message you passed to the exception. - Unhandled exceptions such as
QueryExceptionorNullPointerExceptionarrive with a generic message. This is the same behavior as in LWC, and it is why the Apex side should catch and rethrow.
The extractMessage helper defends against an empty array, which can happen on network failures.
A related gotcha applies to both frameworks. In an Apex test, getMessage() on an AuraHandledException created with the one-argument constructor returns "Script-thrown exception". To assert on the real text, create the exception, call setMessage(...), and then throw it.
Caching in Aura
In LWC, cacheable=true lets the wire service cache results, and refreshApex bypasses the cache. Aura has its own mechanism. You opt in on the client with action.setStorable(), and the Apex method must be @AuraEnabled(cacheable=true). Aura then stores the response on the client and may serve the cached response first, followed by a fresh one that triggers your callback again.
loadContactsCached: function (component) {
var action = component.get("c.getContacts");
action.setParams({ accountId: component.get("v.recordId") });
action.setStorable();
action.setCallback(this, function (response) {
if (response.getState() === "SUCCESS") {
component.set("v.contacts", response.getReturnValue());
}
});
$A.enqueueAction(action);
}Because the callback can run twice for a storable action, it must be safe to repeat. Setting an attribute is safe. Appending to a list or incrementing a counter is not.
There is no refreshApex for Aura. After a write, call a function that enqueues the read action again without setStorable(), as createContact does above when it calls this.loadContacts(component). A non-storable action always goes to the server. If you must keep the storable version, check the Aura documentation for the setStorable options that ignore existing cached values.
A method marked cacheable=true cannot perform DML, in Aura or in LWC. Writes always use a non-cacheable method.
Parameters, return types, and wrappers in Aura
The type rules from earlier chapters carry over, with these Aura-specific notes.
- IDs arrive as strings.
component.get("v.recordId")returns a string, and the framework converts it toId. An invalid ID string fails the call with an error. - SObjects arrive as plain objects. Fields you did not query are missing. Referencing
{!contact.Email}in markup works only if the SOQL selectedEmail. - Wrapper classes work unchanged. For the
Summaryclass from the wrapper chapter,response.getReturnValue()is an object withnameandcontactCount. Only members marked@AuraEnabledare present. - Attribute types should match. If you store a returned list in an attribute, declare it as
ListorContact[]. For a wrapper, useObject. - Overloads remain forbidden. Aura finds methods by name, so two methods with one name cause problems here as well.
Security stays on the server
Everything from the security chapter still applies. Sharing and field-level security come from with sharing and WITH USER_MODE or as user in the Apex class, not from the component. An Aura component cannot weaken or strengthen them. This is one benefit of a shared controller. You secure the class once, and every client that calls it gets the same enforcement.
Choosing a framework for new work
For new components, build in LWC. Use Aura only when the platform requires it, when you are extending an existing Aura component, or when you need a feature that LWC does not support. Keeping the Apex controller framework-neutral makes later migration cheap. Write the Apex once, and when you rewrite the component in LWC, you replace the helper and controller files with a JavaScript class and keep the Apex untouched.
Exercise
An Aura component calls a cacheable=true Apex method with action.setStorable(). The user creates a record through a separate non-cacheable method, but the list still shows old data. Why does refreshApex not help, and what should the component do instead?
Show answer
refreshApex works only with data provisioned by the LWC wire service, and Aura has no wire service. The component should enqueue the read action again after the write succeeds, without calling setStorable() on that action, so the request goes to the server instead of being answered from the client cache.
Exercise
The following Aura helper always shows "Unknown error" for a failed save, even though the Apex method throws new AuraHandledException('Could not create the contact'). What is wrong? action.setCallback(this, function (response) { component.set("v.errorMessage", response.getError().message); });
Show answer
response.getError() returns an array, so .message on the array is undefined. The code must read response.getError()[0].message. It should also check that the array and its first element exist, as the extractMessage helper does.
Exercise
A developer passes { account: component.get("v.recordId") } to setParams for the method getContacts(Id accountId). What happens, and how do you fix it?
Show answer
The key account does not match the Apex parameter name accountId, so the call fails and the callback receives an ERROR state. Rename the key to accountId.