Posted on

How to use GET and SET in Lightning Web Components.

Welcome to SFDCClass first blog. Here, we will try to share some basic Salesforce scenarios which we generally face in our day to day life. The blogs here will contain Salesforce Development ,CPQ and Admin use cases.

In this blog, we’ll learn How to use GET and SET in Lightning Web Components.

In simple language, GET method is used to return the value and SET method is used to set the value.

GET :

GET method always starts with get keyword followed by the name of the method and takes no parameter.

GET method fires by two ways: 1. When you reference a getter method name in your HTML file.

example : {getMethodName}

2. When you refer a getter method name in your JS methods or properties in LWC.

example : this.getMethodName();

SET :

SET method always starts with set keyword followed by the name of the method and always takes one parameter.

SET method will fire automatically when you assign some value to the setter method name in your JS methods.

example : this.setMethodName={value};

Let’s see with an example below:

We have created a Lightning Web Components named gettersetter, here we are trying to convert seconds/minutes/hour/day into milliseconds.

gettersetter.html :

In this file we are using a lightning-input field of type number to enter the number we want to convert to milliseconds, a lighting-combobox to select the options from the drop down (seconds/minutes/hour/day) , a lightning-button which will convert seconds/minutes/hour/day to milliseconds, and a read only lightning-input  base component to display the output in milliseconds.

<template>
    <div class="c-container" style="background-color:white;">
      <lightning-layout>
          <lightning-layout-item padding="around-small">
              <lightning-input data-id="Test" type="number" name="" variant="label-hidden" placeholder="Number to convert" value={numbertoconvert} onchange={handleChange}></lightning-input>
          </lightning-layout-item>

          <lightning-layout-item padding="around-small">
             <lightning-combobox name="" label="" variant="label-hidden" value={selectedOption} placeholder="Select" options={options} onchange={handleSelect}>     </lightning-combobox>
          </lightning-layout-item>

          <lightning-layout-item padding="around-small">
             <lightning-button variant="brand" label="Convert" title="Convert" onclick={handleClick} class="slds-m-left_x-small"></lightning-button>
         </lightning-layout-item>

         <lightning-layout-item padding="around-small">
             <lightning-input type="number" name="" variant="label-hidden" value={convertedValue} disabled="true"></lightning-input>Millisecond
         </lightning-layout-item>
    </lightning-layout>
  </div>
 
</template>

gettersetter.js :

import { LightningElement } from 'lwc';
export default class Gettersetter extends LightningElement {

    numbertoconvert;
    convertedValue;
    selectedOption;

    get options() {
        return [
            { label: '--None--', value: '' },
            { label: 'Second', value: '1000' },
            { label: 'Minute', value: '60000' },
            { label: 'Hour', value: '3.6e+6' },
            { label: 'Day', value: '8.64e+7' }
        ];
    }

    set convert(val) {
        this.convertedValue = val;
    }

    handleChange(event) {
        this.numbertoconvert = event.detail.value;
    }

    handleSelect(event) {
        this.selectedOption = event.detail.value;
    }

    handleClick() {
        this.convert = (this.selectedOption && this.numbertoconvert ? this.numbertoconvert * this.selectedOption : '');
    }
}

Let’s understands what we are doing in our .js file.

We have defined three private attributes:  “numbertoConvert” which will store the value entered in lightning-input, “selectedOption” which will store the selected value from the drop down and “convertedValue” which will store the output.

import { LightningElement } from 'lwc';
export default class Gettersetter extends LightningElement {

    numbertoconvert;
    convertedValue;
    selectedOption;

We have defined one GET method “options()” which will return the list of options and display in the lighting-combobox base component.

get options() {
        return [
            { label: '--None--', value: '' },
            { label: 'Second', value: '1000' },
            { label: 'Minute', value: '60000' },
            { label: 'Hour', value: '3.6e+6' },
            { label: 'Day', value: '8.64e+7' }
        ];
    }

When the user enters a number in lightning-input, handleChange(event) function will invoke which will update the value entered on UI to numbertoConvert attribute.

handleChange(event) {
        this.numbertoconvert = event.detail.value;
    }

When the user selects the option from the dropdown , handleSelect(event) function will invoke which will save the selected value to selectedOption attribute.

handleSelect(event) {
        this.selectedOption = event.detail.value;
    }

Now when the user clicks the Convert button, handleClick() function will invoke where we have assigned the value to this.convert property based on the if-else condition.

handleClick() {
        this.convert = (this.selectedOption && this.numbertoconvert ? this.numbertoconvert * this.selectedOption : '');
    }

When the value is assigned to convert property the SET method “convert(val)” will be invoked automatically where we are assigning the passed parameter to the convertedValue attribute which will display on UI as output in milliseconds.

set convert(val) {
        this.convertedValue = val;
    }

gettersetter.js-meta.xml :

Lastly, we will update the meta-xml file to show the LWC on the home page.

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

Note: If you have any feedback related to the content please feel free to reach out to us.

Leave a Reply

Your email address will not be published. Required fields are marked *