Introduction

The main concepts included in this recipe are:

<aside> 📁 Find this LWC in this folder: force-app/main/default/lwc/ldsDeleteRecord and the Apex class in this folder: force-app/main/default/classes/AccountController.cls

</aside>

Expose an Apex method to LWCs

<aside> ☝ Please review this page before ‣ which help you a lot to understand the basics.

</aside>

The getAccountListin the AccountControllerclass is exposed to LWC using the AuraEnabledannotation:

...
@AuraEnabled(cacheable=true)
public static List<Account> getAccountList() {
    return [SELECT Id, Name FROM Account WITH SECURITY_ENFORCED LIMIT 10];
}
...

What is the cacheable=true useful for?

It is used to improve runtime performance by caching the results on the client side, which avoid repeating the same query saving resources. The downside to this attribute, is that can only be set for methods that do not perform Data Manipulation Language (DML), cannot modify or change data.

Import the Apex method

In order to be used in the Javascript file, an import statement is required considering the class and the method used:

import getAccountList from '@salesforce/apex/AccountController.getAccountList';

Invoking the Apex method from the LWC

This method could be invoked using a wireadapter or imperatively, in this LWC a wiremethod is used:

@wire(getAccountList)
wiredAccounts(result) {
    this.wiredAccountsResult = result;
    if (result.data) {
        this.accounts = result.data;
        this.error = undefined;
    } else if (result.error) {
        this.error = result.error;
        this.accounts = undefined;
    }
}