Wednesday, September 27, 2023

How to call the apex method in lightning web component

 There are two ways to call the Apex method from Lightning Web Component:

  1. Call apex method Using Wire services.
  2. Call the apex method imperatively.

Calling Apex method using wire services in lightning web component:

Using Wire method:

To call the apex method in the lightning web component, First, we have to create the apex class and add the @AuraEnabled method at the first line, i.e., before starting the method. To call it from Wire Service, the method should be cacheable. Hence, add cacheable=true in @AuraEnabled. In the LWC js controller, we need to write the import method using the @salesforce/apex/className.MethodName; at the start of the js controller and in the lightning, we need to write the @wire to get the records we provide in the apex class.

Using Imperatively method:

Calling the apex method in the lightning web component without using the wire method is more accessible than the wire method. Making the AuraEnabled method cacheable is not mandatory to call it imperatively. While using the wire method, we need to add the data, but there is no need for this in the imperatively method. It is the easiest way to call the apex method in the LWC.

For Ex:-

Apex class with the @AuraEnabled:-

AccountController_apexclass
AccountController_apexclass

In JS Controller, we need to import this method using @salesforce/apex/ module like below:

JS controller import method
JS controller import method

For the wire method:

wire method
wire method

To call imperatively:

Imperative method
Imperative method

The above classes and the code will give you a brief idea of calling the apex method in the lightning web component. Using the methods, we can quickly call the apex method and get the data to perform the particular tasks.