Mytutorialrack

How to Call Apex from LWC

Looking to extend your Lightning Web Components with server-side capabilities? Learn the art of how to call Apex from LWC and achieve dynamic and responsive applications.

In the Salesforce Lightning Platform, Lightning Web Components (LWC) provide a modern way to build efficient and reusable components for your applications. One of the powerful features of Lightning Web Components is the ability to interact with the server-side Apex code seamlessly.

How to call Apex from LWC?

You can enhance your Salesforce development skills with insights into how to call Apex from LWC. Gain a comprehensive understanding of both declarative and imperative approaches for a smooth integration experience.

In this blog post, we’ll explore two main methods for calling Apex methods from Lightning Web Components: using the @wire decorator and utilizing imperative calls.

1. Using the @wire Decorator:

The @wire decorator offers a declarative way to connect a Lightning Web Component to an Apex method. This method allows you to fetch data from the server and bind it directly to a property in your component.

The @wire decorator enables you to wire a property or function in your Lightning web component to an Apex method.

The data returned from the Apex method is automatically passed to the wired property or function. Here’s an example of how you can use the @wire decorator to call an Apex method:
Let’s dive into an example:

We have created a ContactSearchController Apex class in which we have defined the method “findContactList“. This method takes in parameter of type string and it returns contact records matching to the search term.

public class ContactSearchController {
@AuraEnabled(cacheable=true)
    public static List<Contact> findContactList(String searchTerm) {
        String searchQuery = '%' + searchTerm + '%';
        System.debug('searchQuery '+searchQuery);
        List<Contact> contactList=[SELECT Id, lastName,firstName, Phone FROM Contact WHERE firstName LIKE :searchQuery LIMIT 10];
        system.debug('contactList '+contactList.size());
        return contactList;
    }
    
}

In the html file, we have created a text box in which we are asking the user to enter the search term and whenever the user manually enters the search term, the results matching to it are shown underneath it.

contactSearchWire.html

<template>
    <div>
        <lightning-input label="Search Contacts" onchange={handleSearchTermChange}></lightning-input>
    </div>
    <template if:true={contacts}>
        <ul>
            <template for:each={contacts} for:item="contact">
                <li key={contact.Id}>
                    {contact.FirstName}  {contact.LastName} {contact.Phone}
                </li>
            </template>
        </ul>
    </template>
</template>

contactSearchWire.js

import { LightningElement,wire } from 'lwc';
import findContactList from '@salesforce/apex/ContactSearchController.findContactList';
export default class SearchContactWire extends LightningElement {
	  searchTerm = '';
    contacts;

    handleSearchTermChange(event) {
        this.searchTerm = event.target.value;
    }

    @wire(findContactList, { searchTerm: '$searchTerm' }) 
    wiredContacts({ error, data }) {
        if (data) {
            this.contacts = data;
        } else if (error) {
            // Handle error
        }
    }
}

2. Using Imperative method

Imperative Apex calls allow you to call Apex methods imperatively using JavaScript code. This gives you more control over when and how you call the Apex methods.

Here’s an example:

ContactSearchImperative.html

<template>
    <div class="container">
        <div class="search-container">
            <label for="searchInput">Search Contact here:</label>
            <lightning-input
                type="text"
                id="searchInput"
                value={searchKey}
                onchange={handleSearchKeyChange}
														 ></lightning-input>
            <lightning-button label="Get Contacts" onclick={handleClick}></lightning-button>
        </div>
        <div class="contacts-container">
            <template if:true={contacts}>
                <lightning-card title="Contacts">
                    <template for:each={contacts} for:item="contact">
                        <div key={contact.Id}>
                            <p>{contact.FirstName} {contact.LastName}</p>
                            <p>{contact.Phone}</p>
                        </div>
                    </template>
                </lightning-card>
            </template>
            <template if:true={error}>
                <p class="error">{error}</p>
            </template>
        </div>
    </div>
</template>

contactSearchImperative.js

import { LightningElement } from 'lwc';
import findContactList from '@salesforce/apex/ContactSearchController.findContactList';

export default class ContactSearchImperative extends LightningElement {
		
		  searchKey = '';
    contacts;
    error;

    handleSearchKeyChange(event) {
        this.searchKey = event.target.value;
				console.log('this.searchKey '+ this.searchKey);
    }

    handleClick() {
				console.log('inside handleClick');
        findContactList({ searchTerm: this.searchKey })
            .then(result => {
                this.contacts= result;
						    console.log('this.contacts '+ this.contacts);
                this.error = undefined;
            })
            .catch(error => {
                this.error = error;
                this.contacts = undefined;
            });
    }
}

Difference between @wire decorator and Imperative Method calls

The difference between using the @wire decorator and imperative method calls in Lightning Web Components (LWC) lies in how you retrieve and handle data from Apex methods.

@wire Decorator:

The @wire decorator is a powerful feature in LWC that provides automatic data binding between your component and the result of an Apex method call. It is typically used when you want to display data directly in your component’s template.

Pros of using @wire:

  • Automatic data retrieval and binding.
  • Cached results are used when possible, improving performance.
  • Data changes are automatically reflected in the component’s rendering.

Cons of using @wire:

  • Limited control over when the data is retrieved.
  • Less flexibility for custom error handling or complex processing.

Imperative Method Calls:

Imperative method calls involve calling Apex methods manually using JavaScript code. You have more control over when and how you fetch and handle data, making it suitable for scenarios where you need more customization.

Pros of using Imperative Method Calls:

  • Control over when the data is retrieved (e.g., based on user actions).
  • Flexibility in handling errors and customizing data processing.
  • Suitable for scenarios where you need to fetch data on-demand.

Cons of using Imperative Method Calls:

  • More manual coding involved.
  • You need to handle caching and error handling explicitly.

Conclusion

Lightning Web Components offer flexible ways to interact with server-side Apex code. Whether you prefer the declarative approach of @wire or the more controlled imperative method, both options empower developers to build dynamic and efficient applications on the Salesforce platform.

Choose the method that best aligns with your component’s requirements and enjoy the seamless integration between LWC and Apex.

Share:

Recent Posts