Call Apex from LWC

In Aura Components you need to export apex method in apex class using @AuraEnabled annotation. In Lightning web component, you need to export as well as import apex method.


Syntax of import method ->



Now to call apex from LWC, first you need to export a method. exporting is similar to Aura Components. Method should be public/global and static and annotated with @AuraEnabled.


e.g.



Imported methods can be called using three ways:

  1. Wire a property

  2. Wire a function

  3. Call a method imperatively


1. Wire a property:

if an method is annotated with @AuraEnabled(cacheable=true), you can invoke method from js file in LWC.


e.g.


2. Wire a function:




In this example, the wire service return the result to wireContacts() function by two objects error and data. If there is any error in calling apex method, error object will have something and will not be null. otherwise 'data' object contain the value returned by apex method. This is why in this example, there are two block inside wiredContacts method. one, where it is executing properly and data is returned and other one where error is returned by apex method.


This code is also available at LWC documentation.


3. Call a method imperatively:

If you want to call an apex method which is not annotated by cacheable=true, you can still call it imperatively.




Import objects and fields:


Here we are importing contacts Name, Title and Email field and using this name field to extract field value using Lightning Data services.



Refresh the Cache for a Wired Property:

When you required to clear cache and loads latest data, then use this functionality. To query the server for updated data and refresh the cache, import and call the refreshApex(wiredProperty) function.



©2019 by SFDC Blogs.