How to Call Apex in Lightning Web Component

How to Call Apex in Lightning Web Component

Hello Trailblazers,

In this blog, we will discuss about how to call Apex in Lighntning Web Component.

Calling Apex in LWC is important as it allows us to perform operations on complex logic. It helps us to access data according to the Salesforce security model.

There are two ways to call the apex method in LWC -

  1. Using wire services
  2. Using Imperative method

Lets deep dive in both methods to understand better with hands on experience:

1. Call Apex using @wire Decorator:

You can @wire a property or a function to receive the data from Apex. You have to annotate your apex method with @AuraEnabled(cacheable=true). By using the wire services it reduces the server call because it loads the data from the cache.

In the below snippet, we have created one apex class ‘DisplayDataInLWC’ in which we have one method ‘fetchAccountUsingWire’ that returns the account’s list where the rating is hot.

Note: Apex method must be static, global or public.

public with sharing class DisplayDataInLWC {
    
        @AuraEnabled(cacheable=true)
    public static List<Account> fetchAccountUsingWire()
    {
        return[SELECT Id,Name,Rating FROM Account WHERE Rating = 'Hot' LIMIT 5];
    }
}        

Now this is our LWC component in which we are displaying the data.

Here in JavaScript, we are importing the Apex method and then invoking it via Apex. The wire service will return the account data else error.

//displayDataSample.js
import { LightningElement,wire } from 'lwc';
import fetchAccountUsingWire from "@salesforce/apex/DisplayDataInLWC.fetchAccountUsingWire";
export default class DisplayDataSample extends LightningElement {

@wire(fetchAccountUsingWire) accounts;
}        

In the template we are using lwc:if directive to check whether data is present or it will return true. A template for:each is used to iterate through the account data.

<!-- displayDataSample.html -->
<template>
  <lightning-card title="Apex Wire" icon-name="custom:custom63">
    <div class="slds-m-around_medium">
      <template lwc:if={accounts.data}>
        <template for:each={accounts.data} for:item="account">
          <li key={account.Id}>{account.Name}</li>
        </template>
      </template>
    </div>
  </lightning-card>
</template>        

Result:

Displaying account list via wire

2. Call Apex Imperatively:?

  1. If we want to invoke our method call on some click or to control our method invocation we have to call the method imperatively.
  2. Calling our method in this way is also helpful if we want to perform some DML operations.
  3. Don’t annotate your method (cacheable=true)? if using via imperative.

Also if we are performing any DML and we are annotating our method with (cacheable=true) it will give you a DMLLimit Exception.

In the below snippet we have created one Apex class DisplayDataInLWC in which we have one method fetchAccountImperative that returns the account’s list where the rating is hot.

//DisplayDataInLWC.apxc
public with sharing class DisplayDataInLWC {
    
    @AuraEnabled
     public static List<Account> fetchAccountImperative()
    {
        return[SELECT Id,Name,Rating FROM Account WHERE Rating = 'Hot' LIMIT 5];
    }

}        

In Template, we are loading the accounts data with the click of the button “Load Accounts”. After clicking it will show us the Account Name.

<!-- displayDataImperatively.html -->
<template>
  <lightning-card title="Apex Imperative" icon-name="custom:custom63">
    <div class="slds-m-around_medium">
      <p class="slds-m-bottom_small">
        <lightning-button label="Load Accounts" onclick={handleClick}></lightning-button>
      </p>
      <template lwc:if={accounts}>
        <template for:each={accounts} for:item="account">
          <li key={account.Id}>{account.Name}</li>
        </template>
      </template>
    </div>
  </lightning-card>
</template>        

In JavaScript, we have one handler that will fire after we click on a button. In this handler, we are invoking our method which will return the list of accounts.

//displayDataImperatively.js
import { LightningElement,track } from 'lwc';
import fetchAccountImperative from "@salesforce/apex/DisplayDataInLWC.fetchAccountImperative";
export default class DisplayDataImperatively extends LightningElement {

@track accounts;
@track error;

handleClick(){
    fetchAccountImperative()
      .then((result) => {
        this.accounts = result;
      })
      .catch((error) => {
        this.error = error;
      });
}
}        

Result:

Displaying account data via imperative call

Difference between @wire and Imperative Call:

  1. As wire is reactive it re-renders every time the data source gets changed.
  2. It reduces the server call which helps to speed up the performance.
  3. With imperatively we can control the apex call.
  4. We can perform DML operations.

Conclusion

This was all about calling Apex in LWC. Calling Apex in Lightning Web Components (LWC) is a crucial aspect of Salesforce development. It provides the means to work with complex logic and access data while adhering to the Salesforce security model. In this blog discussed two methods for calling Apex in LWC: using the @wire decorator and calling Apex imperatively.

In your Salesforce development journey, trying out these methods and experimenting with them is key. If you have any questions or insights to share, feel free to leave them in the comments. Happy coding!

?? Warren Walters

Helping you learn Salesforce Development | Salesforce MVP & C3PO @ Cloud Code ??

1 年

Really cool article. It may be good to mention the lightning/uiRecordApi to try when possible.

要查看或添加评论,请登录

Kashish Bansal的更多文章

  • Parent Child Communication in LWC

    Parent Child Communication in LWC

    In Lightning Web Components, as a developer we sometimes need to share data across different components to break down…

  • Lightning Record Form in Lightning Web Component

    Lightning Record Form in Lightning Web Component

    Lightning-record-form is the base component that provides us with the desired functionality to create, view, and update…

  • How to use lightning/uiRecordApi In LWC

    How to use lightning/uiRecordApi In LWC

    Hello Trailblazers, In this blog, we will discuss how to use lightning/uiRecordApi in LWC. uiRecordApi is the module in…

  • How to Use Lightning Datatable in Lightning Web Component

    How to Use Lightning Datatable in Lightning Web Component

    Hello Trailblazers, In this blog, we will discuss how to create lightning datatable in LWC. Lightning datatable is the…

    5 条评论

社区洞察

其他会员也浏览了