How to call Apex method in Lightning Web Components(LWC)
Gaurav Gupta
Certified System Architect | Certified Application Architect | 19X Certified | Trainer | Double Ranger | Blogger
In this article, we'll delve into two primary approaches to invoke Apex methods from Lightning Web Components.
The wire decorator provides a declarative means to establish a connection between a Lightning Web Component and an Apex method. This approach empowers you to retrieve data from the server and seamlessly bind it to a property within your component.
@wire decorator
We have created a MyApexClass Apex class in which we have defined the method “fetchData“. This method returns a list of strings.
Then we are simply using the @wire decorator in .js file to call the Apex method.
public with sharing class MyApexClass {
@AuraEnabled(cacheable=true)
public static List<String> fetchData() {
// Your Apex logic here
return new List<String>{'Data 1', 'Data 2', 'Data 3'};
}
}
<!-- myLWCComponent.html -->
<template>
<lightning-card title="Apex Method Call Example" icon-name="custom:custom14">
<div class="slds-m-around_medium">
<template if:true={sampleStrings.data}>
<ul>
<template for:each={sampleStrings.data} for:item="item">
<li key={item}>{item}</li>
</template>
</ul>
</template>
</div>
</lightning-card>
</template>
// myLWCComponent.js
import { LightningElement, wire } from 'lwc';
import fetchData from '@salesforce/apex/MyApexClass.fetchData';
export default class MyLWCComponent extends LightningElement {
@wire(fetchData) sampleStrings;
}
Output
Advantages of leveraging @wire:
领英推荐
Drawbacks associated with @wire:
Imperative method
Using Imperative Apex calls enables the invocation of Apex methods through JavaScript code. This grants enhanced control over the timing and execution details of Apex method calls.
Replace the .html and .js code with the below code in the above LWC
<!-- myLWCComponent.html -->
<template>
<lightning-card title="Apex Method Call Example" icon-name="custom:custom14">
<div class="slds-m-around_medium">
<lightning-button label="Fetch Data" onclick={fetchData} variant="brand"></lightning-button>
<template if:true={data}>
<ul>
<template for:each={data} for:item="item">
<li key={item}>{item}</li>
</template>
</ul>
</template>
</div>
</lightning-card>
</template>
// myLWCComponent.js
import { LightningElement, track } from 'lwc';
import fetchData from '@salesforce/apex/MyApexClass.fetchData';
export default class MyLWCComponent extends LightningElement {
@track data;
fetchData() {
fetchData()
.then(result => {
this.data = result;
})
.catch(error => {
console.error('Error fetching data:', error);
});
}
}
Output
Advantages of Leveraging Imperative Method Calls:
Drawbacks associated with Imperative Method Calls:
Select the approach that aligns most effectively with your component's needs and experience the smooth integration between Lightning Web Components (LWC) and Apex.