How to Call Apex Method From Lightning Web Components?

How to Call Apex Method From Lightning Web Components?

On April 24, 2024, Posted by , In Salesforce,Salesforce Apex Tutorial, With Comments Off on 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 the wiredProperty to store the data in a variable.
Here’s an example of how to do this:

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.
Here’s an example of this approach:

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);
            });
    }
}
  1. In this example, getAccountList is again the Apex method you want to call. You can call callApexMethod() in your component’s lifecycle hooks like connectedCallback 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.