LWC: Call Apex Methods in LightningWebComponents


In LightningWebComponents we can call Apex class in three different ways depends on the requirement.

  • Wire a Property
  • Wire a function
  • Call a method imperatively
We will see each method with example and when to use these methods.

In our example we will have apex method to fetch the contacts.We will use the same apex method for all the three examples.So first create a apex class with name getContactList.apxc and use below code.
Note: We need to decorate apex method with @AuraEnabled

Wire a Apex Method to a Property:
  • Apex method should be annotated with @AuraEnabled(cacheable = true) to invoke a apex method via wire service.
  • Go for this method when you don't want to operate any thing on the returned data. ie., when you want to show the data exactly received from apex method with out any changes.
    Syntax:
           @wire(apexMethod, { apexMethodParams })
           propertyOrFunction; 
apexMethodCallProperty.html
   
apexMethodCallProperty.js
   

Wire a Apex Method to a Function:

  • Go for this method when you want to operate on the returned data.
  Syntax: 
        @track param = '';
@track prop;
@track error;

@wire(myApexMethod, {myParam:'param'})
wiredProp({data, error}){
if(data){
this.prop = data;
this.error = undefined;
}
else if (error) {
this.error = error;
this.prop = undefined;
}
}
  apexMethodCallFunction.html
 
 apexMethodCallFunction.js


 Call a Method Imperatively:

  • Call a method imperatively when you must control when the invocation occurs (for example, in response to clicking a button, or to delay loading to outside the critical path)
Syntax:
       param;
      myCallbackMethod() {
          if (this.param) {
             MyapexMethod({ paramVar: this.param })
                 .then(result => {
                     // Success logic...
             })
                 .catch(error => {
                     // Error logic...
                  });
          }
       }
apexMethodCallimperatively.html
 
 apexMethodCallimperatively.js

Happy Lightning!!
Reference: SalesforceGuide

Comments

Post a Comment