Calling Apex from Lightning Web Components in Salesforce


NSIQ Icon
August 19, 2025

apex from lightning web components

Introduction:

Lightning Web Components (LWC) allow us to build fast, modern, and reusable UI in Salesforce.
Sometimes, you need to fetch or update Salesforce data from LWC. For that, you can call Apex methods directly from your component.

1. Why Call Apex from LWC?

You need to call Apex when:

  • You need data from Salesforce that is not available via Lightning Data Service (LDS)
  • You want to perform complex business logic in the backend
  • You need to insert/update/delete records in Salesforce

Example use cases:

  • Fetching filtered records from an object
  • Inserting a record with custom validations
  • Calling an external API from Salesforce via Apex and showing the result in LWC

2. Types of Apex Calls in LWC

 A. Wire Service (@wire)

  • Automatically calls Apex method and refreshes data when parameters change
  • Good for read-only data fetching
  • Reactive

Syntax:

import { LightningElement, wire } from ‘lwc’;
import getAccounts from ‘@salesforce/apex/AccountController.getAccounts’;
export default class AccountList extends LightningElement {
@wire(getAccounts) accounts;
}

B. Imperative Call

  • Manually call Apex when you want (e.g., on button click)
  • Good for creating, updating, or running logic
  • Not reactive — runs only when you call it

Syntax:

import { LightningElement } from ‘lwc’;
import getAccounts from ‘@salesforce/apex/AccountController.getAccounts’;
export default class AccountList extends LightningElement {
handleClick() {
getAccounts()
.then(result => {
console.log(‘Data:’, result);
})
.catch(error => {
console.error(‘Error:’, error);
});
}
}

Example: Fetch Accounts from Apex in LWC

Step 1 – Create Apex Class

public class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts() {
return [SELECT Id, Name, Industry FROM Account LIMIT 10];
}
}

Step 2 – Create LWC JavaScript File

Step 2 – Create LWC JavaScript File

Step 3 – LWC HTML File

Step 3 – LWC HTML File

Conclusion:

Calling Apex from LWC allows you to connect your frontend UI with powerful backend logic in Salesforce.

By using wire and imperative calls properly, you can create fast and efficient Lightning Web Components. If you’re exploring Salesforce Lightning app development in USA, mastering Apex calls in LWC is a key step to building scalable and high-performance applications.