There are two programming models used by Salesforce Lightning Components, one is the Lightning Web Components which are custom HTML elements built with HTML and Javascript, while the other is the original model, Aura Components. Both of these components can coexist with each other and can interoperate on a page appearing as Lightning Components to the admins and end-users.

Lightning Web Components are lightweight and deliver an exceptional performance as they are built on the code running natively in the browsers. Using core web components, LWC provides the needed to perform well on the Salesforce-supported browsers.

Apex is like Java for Salesforce enabling you to interact with the data on the Lightning Platform using classes, data types, variables or if-else conditions. It can either be executed based on conditions or repetitive blocks of code.

Apex Class Methods can be imported into JavaScript Classes by Lightning web Components using ES6 import. After which, apex methods can be called into the components as functions either via using the wire service (@wire) or imperatively wherein the Apex Method should be marked with @AuraEnabled(cacheable=true).

Syntax:

The default syntax to import any Apex Method is

import apexMethodName from ‘@salesforce/apex/

Namespace.Classname.apexMethodReference’;

Wherein,

  • apexMethodNameis an imported symbol that identifies the Apex method.
  • apexMethodReferenceis the name of the Apex method to import.
  • Classnameis the name of the Apex class.
  • Namespace is the namespace of the Salesforce organization.

Apex Method in Salesforce Lightning Web Component can be called by:

  • Wire a property
  • Wire a function
  • Call a method imperatively

For Live Demo Click Here

Exposing Apex Methods to Lightning Web Components:

An Apex method can be exposed to a Lightning Web Component by a static method which is either global or public.

Enabling Client-Side Caching:

Enabling the caching of the method shows the cached data from the client-side storage without waiting for the server to respond. Especially helpful for the users having high latency, slow or unreliable connection, it improves the component’s runtime performance exceptionally.

Enabling the client-side caching by marking the Apex method with @AuraEnabled(cacheable=true) caches the method results on the client’s storage. To set cacheable=true, method must only get data and not update it.

Calling the Apex Method Imperatively:

Set cacheable = true to call the Apex Method Imperatively. It caches the data to the client side’s storage and prevents DML (Data Manipulation Language) operations.

In the case of stale data, get the fresh data by querying to the server for the updated data and refreshed cache using refreshApex().

The cache’s refresh time is the duration of seconds before an entry is refreshed in the storage. It can be configured automatically via Lightning Experience and Salesforce Mobile App.

Using Continuations

Continuation class in Apex calls for a long-running request to an external Web service by using @AuraEnables annotation.

 

  • @AuraEnabled(continuation=true) makes a long-running request to an external Web service.
  • @AuraEnabled(continuation=true cacheable=true) caches the result of the continuation action by setting cacheable=true on the Apex callback method.

Wire an Apex Method to a Property:

The Apex Wire Method can be used on a property or a function and returns a list of accounts. With @AuraEnables (cacheable=true), the apex method can be invoked from a component via wire service. The wire service on a function allows you to operate on the resulted data.

Syntax:

import apexMethod from

‘@salesforce/apex/
Namespace.Classname.apexMethod’;

@wire(apexMethod, { apexMethodParams })

propertyOrFunction;

wherein,

  • apexMethodParams—An object with parameters for the apexMethod, if needed. If a parameter value is null, the method is called. If a parameter value is undefined, the method isn’t called.
  • propertyOrFunction—A private property or function that receives the stream of data from the wire service. If a property is decorated with @wire, the results are returned to the property’s data property or error property. If a function is decorated with @wire, the results are returned in an object with a data property or an error property.

Implementation:

To get this data the component will wire an Apex method. The Apex method makes a SOQL query that returns a list of accounts. To return list of accounts you can use ‘getListUi’ but if you use SOQL query to select certain records then you must use an Apex method.

The Apex method must be static and public or global and should be annotated with @AuraEnabled(cacheable=true).

The component’s JavaScript code imports the Apex method and invokes it via the wire service. The wire service provisions the list of accounts to the accountObj.data property.

The template uses the if: true directive to check whether the accountObj.data property is truthy. If yes then it iterates over it and renders the name of each account.

Now right click on the code editor screen of .xml and click on ‘SFDX: Deploy This Source to Org’. Similarly deploy the Apex class. Once the code is successfully deployed the success status will be shown on the output screen.

Now In your salesforce org, edit the home page and add the custom Lightning web component to the page.

This is everything you need to know about the calling Apex Method in Lightning web components. For any assistance in understanding Apex Method, please reach out to our expert team at sales@hicglobalsolutions.com.

Related Articles
Please Make Blog Banner How to Create an Agentforce Enabled Scratch Org in Salesforce 100 1

Setting up an Agentforce-enabled scratch org is the most important step for developers who want to experiment with AI features such as Prompt Builder and Einstein GPT. Whether you’re developing the next generation CRM software or experimenting with how generative AI may improve user experience, a scratch org equipped with Agentforce is your playground. Follow […]

Read More
Step-by-Step Guide to Enhance Your LWC Development Workflow with the Logger API

Are you looking to streamline your LWC development workflow but confused about how to do it? Then you are in the right place. The Salesforce Logger API is a powerful tool that helps you monitor, debug, and improve code quality in real time.  This step-by-step guide walks you through how to set it up and […]

Read More
Enhancing Your Salesforce Experience with a Custom Activity Component

In today’s fast-paced business landscape, productivity hinges on streamlined workflows and intuitive interfaces. While Salesforce offers robust activity tracking capabilities, sometimes the standard components fall short of specific organizational needs.  That’s where a Custom Activity Component comes in—designed to tailor your activity management experience, boost user efficiency, and provide deeper insights into customer interactions. In […]

Read More
Step-by-Step Guide to Integrating Salesforce Doc-Gen with eSigning Tools

In today’s fast-paced digital landscape, streamlining document workflows is no longer a luxury—it’s a necessity.  Integrating a document generation app, like Docs Made Easy, with an eSigning tool, helps businesses automate the entire document lifecycle—from creation to signature—saving time, reducing errors, and boosting productivity. In this guide, we’ll walk you through the key steps, tools, […]

Read More
How to Build a Real Time Chat Application Using LWC and Models API

The Models API plays a significant role in providing access to and facilitating interaction with large language models (LLMs) from various Salesforce partners such as Anthropic, Google, and OpenAI. It enables applications to leverage these models for various tasks, including text generation and other AI-powered capabilities. As a user, you can configure any Salesforce-enabled model […]

Read More
How to Integrate Salesforce Data Cloud with Amazon Redshift

Companies can finally connect Amazon Redshift to Salesforce Data Cloud without using the ordinary username & password authentication systems ever since its collaboration with AWS has happened. Business owners no longer have to be concerned about managing static credentials or breaching data security. By leveraging Salesforce IDP, companies can easily access their data lakehouse in […]

Read More
Our Location worldwide
Indian Flag India
3rd Floor, A-10, Pegasus Tower, Sector 68, Noida, Uttar Pradesh 201301 +91-1203117884
United States of America Flag USA
333 West Brown Deer Road Unit G – 366 Milwaukee WI, USA 53217 +1(262) 310-7818
United Kingdom Flag UK
7 Bell Yard, London, WC2A 2JR +44 20 3239 9428
Canada Canada
HIC Global Solutions INC
43 Lafferty Lane, Richmond Hill, L4C 3N8, CA +1(262) 310-7818