How to call Apex method in Lightning Web Components(LWC)

How to call Apex method in Lightning Web Components(LWC)

In this article, we'll delve into two primary approaches to invoke Apex methods from Lightning Web Components.

  1. @wire decorator
  2. Imperative method

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:

  1. Automated data retrieval and binding.
  2. Enhanced performance through the utilization of cached results when applicable.
  3. Automatic synchronization of data changes with the component's rendering.

Drawbacks associated with @wire:

  1. Restricted control over the timing of data retrieval.
  2. Reduced flexibility for implementing custom error handling or intricate processing logic.

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

On clicking the Fetch Data button

Advantages of Leveraging Imperative Method Calls:

  1. Control over when the data is retrieved (e.g., based on user actions). We can not call wire adapters based on events.
  2. Flexibility in customizing data processing.
  3. Applicability in situations requiring on-demand data retrieval.

Drawbacks associated with Imperative Method Calls:

  1. Involves a higher degree of manual coding.
  2. Explicit management of caching and error handling is required.

Select the approach that aligns most effectively with your component's needs and experience the smooth integration between Lightning Web Components (LWC) and Apex.

要查看或添加评论,请登录

Gaurav Gupta的更多文章

社区洞察

其他会员也浏览了