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. 

When we call a method imperatively, we receive only a single response. 

However with @wire, it delegates control to the framework and results in a stream of values being provisioned.

Let us understand with a simple example,



    <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}








        <template if:true={error}>


            Some error occured.







import { LightningElement,track } from 'lwc';

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

export default class GetAccountDataImperatively extends LightningElement {

    @track accountRecord;

    @track error;

    @track accName;




        const userInput =;


        this.accName= userInput;




    handleChangeMethod() {


            accNameParamInApex : this.accName


            .then(result => {

                this.accountRecord = result;


            .catch(error => {

                this.error = error;






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

<LightningComponentBundle xmlns="">





public with sharing class customAccountController {

    public customAccountController() {




    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;








How to call an apex method imperatively in lwc

No comments:

Post a Comment