Salesforce | How to Call the Apex Method Imperatively in Lightning Web Component?

When we want to control when a method should be invoked (for instance, in response to a button click), we use an imperative method call. 

We only get one response when we call a method imperatively. 

With @wire, on the other hand, it cedes authority to the framework and causes the provisioning of a stream of values. 

Annotate the Apex method with @AuraEnabled(cacheable=true) if you want to utilize @wire to call it. Before making a network call to the server to call the Apex method, a client-side Lightning Data Service cache is checked. 

The following situations require you to contact an Apex method directly, rather than through @wire. 

  • To invoke any method that inserts, modifies, or deletes data and isn’t tagged with cacheable=true. 
  • To regulate when the invocation takes place. 
  • To work with objects like Task and Event that User Interface API does not provide. 
  • Using an ES6 module’s method call that does not extend LightningElement 

Don’t forget to check out: Learn All About the Batch Apex in 2023

Before making a network request to the server to call an Apex method tagged with @AuraEnabled(cacheable=true), the client-side Lightning Data Service cache is examined. However, Apex-provisioned data is not managed by Lightning Data Service. As a result, to update the Lightning Data, execute getRecordNotifyChange() after calling the Apex method. 

Let us understand with a simple example- 


    <lightning-card title="Imprerative Demo"> 
        <div style="height: 200px"> 


import { LightningElement,track } from 'lwc'; 
import  getCntDetails from '@salesforce/apex/ImperativeMethods.getCntDetails'; 
const columns=[ 
    {label:"Contact Id",fieldName:"Id"}, 
    {label:"Contact Name",fieldName:"Name"}, 
    {label:"Account Name",fieldName:"AccountId"}, 
export default class ImperativeMethod extends LightningElement { 
    @track columns=columns; 
    @track data=[]; 
        .then(result =>{ 
            .catch(error =>{ 
                console.log("error occurd"); 

dont miss out iconCheck out another amazing blog by Narendra Kumar here: Navigation Service in Lightning Web Component | All You Need to Know


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


public with sharing class ImperativeMethods { 
    public static list<Contact> getCntDetails() { 
        list<Contact>contactDetails=[select Id,Name,AccountId from Contact]; 
        return contactDetails; 



Source link

Interesting Posts

Leave a Reply

Your email address will not be published. Required fields are marked *