How to make the code Reusable in LWC

AURA

Re-usability means a common service component that’s allow multiple developers to access existing code or they can add extra code for reusable. We need to focus on re usability in LWC, so for this approach we need to use service component.

In this blog we are getting Account and Contacts list by Service component.

apexService.js

import fetchAccounts from '@salesforce/apex/AccountController.getAccounts';
import fetchContacts from '@salesforce/apex/ContactsFromAccount.getContactList';

const fetchAccountList  = async () => {
    try {
        const result_1 = await fetchAccounts();
        return result_1;
    } catch (error) {
        console.log(error);
    }
}

const fetchContactList = async (recId) => {
     try {
        const result = await fetchContacts({ accId: recId });
        return result;
    } catch (error) {
        console.log(error);
    }

    
}

export {fetchAccountList ,fetchContactList }

above component will import in below component:-

CommonComponent.html

<template>
    <lightning-card title="How to use Service component For Account" icon-name="custom:custom14">
        <ul class="slds-m-around_medium">         
            <template for:each={accountList} for:item= "acc">
                <li key={acc.Id}>{acc.Name}</li>
            </template>
        </ul>
    </lightning-card>

    <lightning-card title="How to use Service component For Contact" icon-name="custom:custom14">
        <ul class="slds-m-around_medium">         
            <template for:each={contactList} for:item= "con">
                <li key={con.Id}>{con.LastName}</li>
            </template>
        </ul>
    </lightning-card>
    
</template>

CommonComponent.js

import { api, LightningElement } from 'lwc';
import { fetchContactList,fetchAccountList  } from 'c/apexService';

export default class CommonComponent extends LightningElement {
    accountList;
    contactList;
    items;
    @api recordId;
    async connectedCallback(){       
      this.accountList = await fetchAccountList();
      this.items  =  await fetchContactList(this.recordId);
      this.contactList = this.items;
    console.log('this.accountList ==>> '+this.accountList);
    console.log('this.contactList ==>> '+this.contactList);
    }  

}

CommonComponent.js-meta.xml

<?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__RecordPage</target>
    </targets>
</LightningComponentBundle>

AccountController.cls

public with sharing class AccountController {
    
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccounts() {
         return [SELECT Id, Name, Phone FROM Account LIMIT 5];
    }
}

ContactsFromAccount.cls

public without sharing class ContactsFromAccount {
    @AuraEnabled (Cacheable = true)
    public static List<Contact> getContactList(String accId){       
        List<Contact> conList = new List<Contact>();
        try {
            conList = [Select Id, FirstName, LastName , Title, Email from Contact where AccountId =: accId ];
            
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
        return conList;
    }
}

5 comments

Leave a Reply