Saturday, January 16, 2021

How to call an apex method imperatively in lwc?

In this blog post we will learn "How to call an apex method imperatively in lwc".

If we want to control when the method invocation should occurs (for example, in response to clicking a button) than we call the method imperatively. 

The "getAccountDataImperatively" Lightning Web Component (LWC) is designed to facilitate the dynamic retrieval of Account records from Salesforce by allowing users to input an Account Name and trigger a search. The LWC employs an imperative approach to invoke an Apex method for fetching data based on user input.

Key Features:

User Input Section:

The component provides a user-friendly interface with a Lightning input field labeled "Enter Account Name." Users can type in the Account Name they want to search for.

Search Button:

A "Search Account" button is available, and users can initiate the search by either pressing the button or changing the content of the input field. The button is configured to invoke the handleChangeMethod function upon clicking.

Display Section:

The component displays retrieved Account information dynamically. The Account Name is presented in a paragraph element, and if there are multiple records matching the search criteria, they are rendered in a loop using the <template for:each> directive.

Error Handling:

The LWC handles potential errors gracefully. If an error occurs during the Apex method invocation, an error message is displayed, ensuring a smooth user experience.

Implementation Details:

Imperative Apex Call:

The handleChangeMethod function in the JavaScript file, "getAccountDataImperatively.js," initiates an imperative Apex call using the getAccountRecordMethod from the "customAccountController" Apex class. The Account Name entered by the user is passed as a parameter to the Apex method.

Asynchronous Handling:

The asynchronous nature of the Apex call is managed using JavaScript Promises. The then block is executed upon successful retrieval of data, updating the accountRecord property with the fetched records. In case of an error, the catch block updates the error property, and an error message is displayed.

Let us understand with a simple example,

getAccountDataImperatively.html

<template>

    <div >

 

        <lightning-input type="text" label="Enter Account Name" value={accName} onchange={handleChange}> </lightning-input>

        <lightning-button variant="base" label="Search Account" title="Search Account" onclick={handleChangeMethod} class="slds-m-left_x-small"></lightning-button>

        <p>Displaying Account Information</p>

 

        <template if:true={accountRecord}>

 

            <template for:each={accountRecord} for:item="item" for:index="index">

 

                <p key={item.Id}>

 

                   Name: {item.Name}

 

                </p>

 

            </template>

 

        </template>

 

        <template if:true={error}>

 

            Some error occured.

 

        </template>

 

    </div>

</template>


getAccountDataImperatively.js

import { LightningElement,track } from 'lwc';

import getAccountRecordMethod from '@salesforce/apex/customAccountController.getAccountRecordMethod';

export default class GetAccountDataImperatively extends LightningElement {

    @track accountRecord;

    @track error;

    @track accName;

 

    handleChange(event){

 

        const userInput = event.target.value;

 

        this.accName= userInput;

 

    }

 

    handleChangeMethod() {

        getAccountRecordMethod({

            accNameParamInApex : this.accName

        })

            .then(result => {

                this.accountRecord = result;

            })

            .catch(error => {

                this.error = error;

            });

    }

   

}



getAccountDataImperatively.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>50.0</apiVersion>

    <isExposed>false</isExposed>

</LightningComponentBundle>


customAccountController.cls

public with sharing class customAccountController {

    public customAccountController() {

    }

    @AuraEnabled

    public static List<Account> getAccountRecordMethod(String accNameParamInApex) {

        String accNameKey = '%'+accNameParamInApex+'%';

       List<Account> accList=[SELECT Id, Name, Industry

        FROM Account

        Where name Like: accNameKey];

        return accList;

    }

}


testingLWCCompApp.app

<aura:application>

<c:getAccountDataImperatively></c:getAccountDataImperatively>

</aura:application>       


Output:

How to call an apex method imperatively in lwc
cacheable=true is not needed when making an imperative call to an Apex method in LWC.

For imperative Apex calls, you do not need to use cacheable=true since the call is directly 
controlled and not automatically cached.

The cacheable=true annotation is only required when using the wire service in LWC to fetch data. 
It enables the Lightning Data Service (LDS) to cache the results and reuse them when the same data is requested again, improving performance.

1 comment:

  1. In the apex method there shouldn't be cachable=true as its an imperative call.

    ReplyDelete