Sunday, 10 January 2021

Usage of utility classes in Lightning web component:

In this demo, explaining about the usage of utility classes in Lwc. I have created utility class inside the  component folder. Utility class name is "Utilityhelper".

Utility helper is referred in component of JavaScript Like below :

import {add,subfrom './utilityhelper.js';

Complete code Snippet:

shareCode.html

<template>
    <lightning-card title="Usage of Javascript Utility Classes">
    <p> add : {resultFromHelper} </p>
    <p> sub : {substractVal} </p>
</lightning-card>
</template>

Javascript

import { LightningElement } from 'lwc';
import {add,subfrom './utilityhelper.js';
export default class UtilityComponent extends LightningElement {
    resultFromHelper;
    substractVal ;
    constructor(){
        super();
        const result = add(1,9);
        this.resultFromHelper=result;
        this.substractVal=sub();
 }
}

xml

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

utilityhelper

/** helper class */
function add(a,b){
  return a+b;

}

function sub(a,b){
  return 5-3//Hardcoded 
}
export{add,sub};