Call Apex Method in LWC (Imperatively and Wire Service)

In the previous post, we created and displayed the record using Lightning Data Service in Lightning Web Component which you can check here. In this post, we will implement the functionality to Call Apex Method in LWC(Lightning Web Component) using Wire Service and Imperatively.

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

  1. Call Apex Method Using Wire Service
  2. Call Apex Method Imperatively

Implementation

In this implementation, we will create a Text box to get the Account Name from the User. As soon as the user starts entering Account Name, we will call the Apex method to get and display the list of Accounts.

Call Apex Method Using Wire Service in LWC

First, create an Apex Class AccountController and add @AuraEnabled method getAccounts that will:

  • Return List of Accounts
  • Accepts strName String parameter to match with Account Name

In order to call it from Wire Service, the method should be cacheable. Hence, add cacheable=true in @AuraEnabled.

AccountController.cls

public class AccountController {
     
    @AuraEnabled(cacheable=true)
    public static list<Account> getAccounts(String strName){
        String strNameLike = '%' +strName +'%';
        return [SELECT Name, AccountNumber FROM Account WHERE Name LIKE :strNameLike];
    }
}

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

import accounts from '@salesforce/apex/AccountController.getAccounts';

Wire Service

Then, we can use accounts adapter in Wire Service like below:

@wire (accounts, {strName:'$strSearchText'})
lstAccount;

where accounts are the adapter that we imported. strName is the parameter that we need to pass to the Apex method getAccounts. Make sure that the value for strName is passed using $ like $strSearchText to make it dynamic so that every time strSearchText is updated, Wire Service can be executed. lstAccount is the property that will store the response of Wire Service. We can access the list of Accounts using lstAccount.data. Add method changeSearchText which is onchange handler that will be called when the input text is changed. Store the search text value in strSearchText.

fetchAccounts.js

import { LightningElement, wire } from 'lwc';
import accounts from '@salesforce/apex/AccountController.getAccounts';
export default class FetchAccounts extends LightningElement {
    strSearchText;
    @wire (accounts, {strName:'$strSearchText'})
    lstAccount;
    changeSearchText(event){
        this.strSearchText = event.target.value;
    }
}

In HTML file, we will loop through the lstAccount.data using for:each and display it on UI.

fetchAccounts.html

<template>
    <lightning-card title="Search Accounts">
        <lightning-layout>
            <lightning-layout-item size="6">
                <!-- Displaying Accounts. -->
                <div class="slds-p-left_medium">
                    <lightning-input placeholder="Enter Account Name" onchange={changeSearchText}></lightning-input>
                    <br/>
                    
                    <!-- To display accounts if list is not null-->
                    <template for:each={lstAccount.data} for:item="acc">
                        <div key={acc.Id} class="slds-p-around_medium lgc-bg">
                            <lightning-tile label={acc.Name} type="media">
                                <lightning-icon slot="media" icon-name="standard:groups"></lightning-icon>
                                <p class="slds-truncate">
                                    <lightning-formatted-text value={acc.AccountNumber}></lightning-formatted-text>
                                </p>
                            </lightning-tile>
                        </div>
                    </template>
                    
                </div>
            </lightning-layout-item>
        </lightning-layout>
    </lightning-card>
</template>

In this way, you can Call Apex Method Using Wire Service in LWC.

Call Apex Method Imperatively in LWC

To call the apex method imperatively, we need to import the method from @salesforce/apex/ module in variable accounts. Then we can use this variable to call the method and pass the parameters if required. This method will return the Promise. Hence we need to handle the Success and Failure response using then and error function respectively. In this approach, we can call this method from onchange handler changeSearchText() so that it will be called every time the search text is updated.

Create the lstAccount track property to save the list of accounts and use the same to iterate on UI. We don’t have to use lstAccount.data here.

accounts({strName: this.strSearchText}).then(response => {
	this.lstAccount = response;
}).catch(error => {
	console.log('Error: ' +error.body.message);
});

This is enough to Call Apex Method Imperatively in LWC. It is not mandatory to make the AuraEnabled method cacheable to call it imperatively.

Call Apex Method in LWC

This is how our implementation looks like:

Call Apex Method in LWC (Apex Call in LWC)
Call Apex Method Using Wire Service in LWC (Apex Call in LWC)

This is how we can Call Apex Method Using Wire Service and Imperatively in LWC LWC (Lightning Web Components).

If you want to know more about this, you can check the official Salesforce documentation here. If you don’t want to miss new posts, you can Subscribe here. Thanks!

2 thoughts on “Call Apex Method in LWC (Imperatively and Wire Service)”

  1. Hi Nikhil
    One thing I want to understand in wire method is the timing of execution. In case of imperative, it is called inside onchange method but the wire adaptor is done outside on change method. how does it work in wire. I did some research in the past and in one of the post, a person has mentioned it runs after connectedcallback. Is it true?

    • It is mentioned in the post itself, “Make sure that the value for strName is passed using $ like $strSearchText to make it dynamic so that every time strSearchText is updated, Wire Service can be executed”.

Comments are closed.