Salesforce Interview Questions & Answers Book is now available!

Grab Now

LWC

Invoke Apex method imperatively in LWC

Let's look at how to invoke apex methods imperatively in LWC

By Teja, ex-Salesforce engineer · Updated March 15, 2021 · 1 min read

Just like Aura Components in Lightning Web Components also we can invoke Apex methods.

So Apex is going to act like server-side technology in case of both Aura Components and Lightning Web Components.

In this post let's look at how to invoke Apex methods from Lightning Web Components imperatively.

We can also invoke Apex methods from Lightning Web Components by using @wire decorator.

Let me quickly walk you through the difference, in the imperative approach, we will invoke the Apex method on click of a button or click (method gets invoked on click of a button or link) whereas with @wire decorator we will invoke the Apex method automatically after the component is initialized.

Here is the snippet to invoke the component Imperatively!

public with sharing class CustomAccountController {
  public CustomAccountController() {
  }

  @AuraEnabled(cacheable=true)
  public static Map<Id, Account> getAccounts() {
    Map<Id, Account> accountsMap = new Map<Id, Account>(
      [SELECT Id, Name FROM Account]
    );
    return accountsMap;
  }
}

customAccountController.cls

import { LightningElement, wire } from "lwc";

import getAccounts from "@salesforce/apex/CustomAccountController.getAccounts";

export default class ExpCustomAccountsComponent extends LightningElement {
  handleClick() {
    getAccounts()
      .then((result) => {
        console.log(data);
      })
      .catch((error) => {
        console.log(error);
      });
  }

}

customAccountComponent.js

<template>
    <lightning-button label="Get Data" onclick={handleClick}></lightning-button>
</template>

customAccountComponent.html

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>51.0</apiVersion>
        <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets> 
</LightningComponentBundle>

customAccountComponent .js-meta.xml

Hope this was helpful!

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion — one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts