Introduction
Sometimes, neither the lightning-record-*-form
components nor the pre-configured wire adapters suit a particular use case. For example, when you want to customize a single-record data transaction, or perform multi-record operations on a single transaction, Apex is the best choice.
There are several ways to interact with Apex methods from LWC:
- Execute the method with
@wire
to a property
- Execute the method with
@wire
to a function
- Call the method imperatively
Limitations
- The LWC framework tracks the Apex actions to send to the server. When the browser finishes processing events and JavaScript on the client, the enqueued actions on the stack are sent to the server in a batch. The framework returns a 413 HTTP response status code if there are more than 2,500 actions in a boxcar request. If a user sees this rare error, consider redesigning your custom component to follow best practices and reduce the number of actions in a request.
Exposing an Apex method
For an Apex method to be accessible from LWC, it is required:
- To Annotate the Apex method with
@AuraEnabled(cacheable=true)
making the method available to LWC. When an @AuraEnabled
method is cacheable, Data Manipulation Language (DML) operations are not allowed.
- The method must be
static
and either global
or public
.
<aside>
☝ When a method is cacheable, newly added or changed versions of records may not be returned until the cache is refreshed.
</aside>
Parameter types supported
Only the following types are supported for input and output:
- Primitive—Boolean, Date, DateTime, Decimal, Double, Integer, Long, and String.
- sObject—standard and custom sObjects are both supported.
- Apex—an instance of an Apex class.
- Collection—a collection of the other types, which is the most common for output values.