
How to Call Apex Method From Lightning Web Components?

To call an Apex method from a Lightning Web Component (LWC) in Salesforce, you need to use the @wire
decorator or JavaScript functions. Here are two common approaches:
Using @wire
Decorator:
- Import the method from your Apex class in your LWC JavaScript file.
- Use the
@wire
decorator to call the Apex method and retrieve data. You can use thewiredProperty
to store the data in a variable.
import { LightningElement, wire } from 'lwc';
import getAccountList from '@salesforce/apex/YourApexClass.getAccountList';
export default class MyLWCComponent extends LightningElement {
@wire(getAccountList)
wiredAccountList;
get accountList() {
return this.wiredAccountList.data;
}
}
In this example, getAccountList
is the Apex method you want to call.
Using JavaScript Function:
- Import the method from your Apex class in your LWC JavaScript file.Create a JavaScript function to call the Apex method using
import
and then call this function when needed.
import { LightningElement } from 'lwc';
import getAccountList from '@salesforce/apex/YourApexClass.getAccountList';
export default class MyLWCComponent extends LightningElement {
accountList = [];
connectedCallback() {
this.callApexMethod();
}
callApexMethod() {
getAccountList()
.then(result => {
this.accountList = result;
})
.catch(error => {
console.error('Error calling Apex method: ', error);
});
}
}
- In this example,
getAccountList
is again the Apex method you want to call. You can callcallApexMethod()
in your component’s lifecycle hooks likeconnectedCallback
or in response to user interactions.
Remember to replace 'YourApexClass'
with the actual name of your Apex class and method. Also, make sure your Apex method is marked as @AuraEnabled
to be accessible from Lightning components.
Comments are closed.