Calling Apex methods in Salesforce Lightning web components

Originally published as ¿Cómo Llamar Apex en Lightning Web Component?

 

One of the features that Salesforce gives us is the ability to call Apex methods in Lightning web components. This can be done by importing the method and calling it with the decorator wire service or imperatively.

Calling Apex methods in Salesforce Lightning web components

How to import an Apex method in a Lightning web component?

We can import methods from Apex classes into a component using the import form in ES6 (ECMAScript v6). This way:

  • apexMethodName: Symbol to identify the Apex method.
  • apexMethodReference: Name of the Apex method that we are going to import.
  • Classname: Name of the Apex class in Salesforce.
  • Namespace: If the Apex class is in the same namespace as the component, do not specify a Namespace. If the class is in a managed package, specify the namespace of the managed package.

 

How to expose an Apex method in Lightning web components?

To expose a method of an Apex class in a component, the method must be static and global or public. Also, we need to add the @AuraEnabled annotation to it.

In the following example, we expose a method called getContactList in the component, which returns a list of contacts.

 

 

How to call an Apex method with React Wire?

To read data from Salesforce, the Lightning web component can use the Reactive Wire service. The wire decorator is used to call an Apex method.

In the following example, we call an Apex method using the wire decorator.

 

How to call an Apex method imperatively?

In the next example, we call an Apex method, which returns a list of contacts, imperatively. The imported function returns a promise.

If you are looking for Salesforce technical content in Spanish written by experts, we recommend visiting Snake on Code, where you will find more information regarding Lightning web components, Apex, and more. 

If you enjoyed this article, here are some more that you might enjoy:

You might also like

Read Next!