Reusable Apex Method Caller Function In Service Lightning Web Component

Lightning Web Component developers always looks for building reusable code. We are going to talk about building a service component which calls an reusable apex method inside a function. The idea is to share the code with other Lightning Web Component to make more generic solutions. We need to export the function in service component. Any other Lightning Web Component can make use of shared reusable apex method caller function by importing the service component.

BUSINESS USE CASE – SERVICE COMPONENT

Architect asked one of its developer to build a service component which basically calls a reusable apex method and share code with others. Several other members from the team has to reuse the same service component in their user story development. Service component should export the function and return the result.

CODE WALKTHROUGH

We are going to build two component to understand the concept of service component.
1. apexService – HTML file is not mandatory for service components
2. apexServiceCaller

We also need an apex class which will be used in service component. The name of apex class is accountController.

accountController.cls

public with sharing class accountController {
    @AuraEnabled
    public static List<Account> fetchAccounts(){
        try {
            return [select id, Name from Account limit 10];
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}

apexService.js

getAccounts function in service component makes call to apex method and return the result. Later on getAccounts has been exported.

import fetchAccounts from '@salesforce/apex/accountController.fetchAccounts';

const getAccounts = () => {
    return fetchAccounts().then((result) => {
        return result;
    }).catch((error) => {
        console.log(error);
    });
};

export { getAccounts };

apexService.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>false</isExposed>
</LightningComponentBundle>

apexServiceCaller.html

HTML is showing a list of account names returned from reusable apex method caller service component. We are storing the returned list in accountList property in JS file of the component.

<template>
    <lightning-card title="Service Component Demo" icon-name="custom:custom14">
        <ul class="slds-m-around_medium">
            <template for:each={accountList} for:item="account">
                <li key={account.Id}>
                    {account.Name}
                </li>
            </template>
        </ul>
    </lightning-card>
</template>

apexServiceCaller.js

We are calling the service component exported function on load of the component. We are using async/await to make sure the promises are resolved.

import { LightningElement } from 'lwc';
import { getAccounts } from 'c/apexService';
export default class ApexServiceCaller extends LightningElement {
    accountList;
    async connectedCallback() {
        this.accountList = await getAccounts();
        console.log('account list', this.accountList);
    }
}

apexServiceCaller.js-meta.xml

This is exposed to app, home and record pages in lightning experience.

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

DEMO – Reusable Apex Method Caller Function

Reusable Apex Method Caller Function

2 comments

Leave a Reply