Getters and Setters in LWC

Getters and Setters in LWC

On November 29, 2022, Posted by , In LWC Tutorial, With Comments Off on Getters and Setters in LWC
Getters and Setters in LWC

We already discussed the utility of getters, how if we want to display the result of expression we can use getters as HTML doesn’t know to allow to compute an expression on the go.

Setters are used if I want to execute a custom logic every time a value of a property is being set. 

In an earlier example, we saw how we created multiple public properties, we can also create getter/setter for the same as well. 

We will have to follow the same step ie mark either of getter or setter as @api (It is recommended to always mark getter as @api as per standards)  

Note: Setter can’t exist alone ie if you are writing a setter you must also write getter, while there are no such criteria for getter variables.

Example: 

Child Component 

We are using if:true and for:each directive which we already understood in previous topics to show filteredHeroes.

In the below javascript file, if you notice we have a public getter/setter where the parent is setting data.

CRS Info Solutions offers real-time Salesforce course for beginners designed to equip learners with practical knowledge and industry skills in Salesforce. Enroll for demo today.

If you’re preparing for a Salesforce developer role, it’s essential to brush up on your knowledge of Lightning Web Components (LWC). To help you ace your interview, we’ve compiled a comprehensive list of LWC interview questions and answers that cover the fundamentals, best practices, and advanced concepts of LWC development. Check out our guide to boost your confidence and increase your chances of success.

Further in the setter, we are calling a function filterData, which is filtering data sent by parents based on ranking.

You must be thinking, we earlier read data passed from a parent is read-only then how are we filtering data?

It’s possible because the filter method ( Array method )  returns a new array and doesn’t make any changes to existing data.

Code ->

-------JS-------
import {
  LightningElement,
  api
} from "lwc";
export default class GetterSetterChild extends LightningElement {
  heroData;
  filteredHeroes;
  @api
  get parentData() {
    return this.heroData;
  }
  set parentData(value) {
    this.heroData = value;
    this.filterHeroes();
  }
  filterHeroes() {
    this.filteredHeroes = this.heroData.filter((item) => item.ranking <= 3);
  }
}

---------END------

-----HTMl------

<template>
    <lightning-card variant="Narrow" title="Heroes" icon-name="standard:account">
        <div class="slds-var-m-around_medium">
            <template if:true={filteredHeroes} for:each={filteredHeroes} for:item="hero">
                <li key={hero.id}>{hero.name}</li>
            </template>
        </div>
    </lightning-card>
</template>

Parent Component 

Both HTML and js files of the parent component are self-explanatory.

Code →

-----JS-----
import { LightningElement } from "lwc";
export default class GetterSetterExample extends LightningElement {
  superHeroes = [
    {
      id: "A1",
      name: "Superman",
      ranking: 1
    },
    {
      id: "A2",
      name: "Batman",
      ranking: 2
    },
    {
      id: "A3",
      name: "Flash",
      ranking: 3
    },
    {
      id: "A4",
      name: "Aquaman",
      ranking: 4
    },
    {
      id: "A5",
      name: "Wonder woman",
      ranking: 3
    }
  ];
}

------END-------

------HTML-----

<template>
    <c-getter-setter-child parent-data={superHeroes}></c-getter-setter-child>
</template>

Boolean Properties

Like other primitive or non-primitive properties we can also pass boolean properties from parent to child but they are passed differently. 

Few points to always keep in mind when using boolean properties. 

  1. The default value of the boolean property should be always false ie @api someName = false.
  2. If the parent component adds the attribute in the child component it’s considered true.
  3. For false we just need to remove the attribute. 

Note: Passing value like some-name =”false” won’t make it false, actually it will be considered as positive.

Note: Default value should always be false, as otherwise there is no other way to toggle the value to false if you set the default value to true.

Let’s understand these more in detail with examples.

Child Component: 

We are simply using if:true and if:false directive on the showdata attribute to render different part.

Code ->

-----JS------

import { LightningElement, api } from "lwc";
export default class BooleanPropChild extends LightningElement {
  @api showData = false;
}

------END-----

----HTML-------
<template>
    <div class="slds-var-m-around_medium" if:true={showData}>
        Attribute passed from parent, hence rendering if:true content
    </div>
    <div class="slds-var-m-around_medium" if:false={showData}>
        Attribute not passed, hence rendering if:false content
    </div>
</template>

Parent Component : 

showData is by default false hence when the parent component doesn’t pass anything, showData false value is considered, and if:false part is rendered

Notice how we have just added “show-data” attribute and not show-data = true because only the presence of boolean property as attribute marks it as true and absence as false.

Code →

-------HTML------
<template>
    <lightning-card variant="Narrow" title="Attribute" icon-name="standard:account">
        <div class="slds-var-m-around_medium">
            <c-boolean-prop-child show-data></c-boolean-prop-child>
        </div>
    </lightning-card>
    <lightning-card variant="Narrow" title="No Attribute" icon-name="standard:account">
        <div class="slds-var-m-around_medium">
            <c-boolean-prop-child></c-boolean-prop-child>
        </div>
    </lightning-card>
</template>

Note: We can always set boolean properties dynamically using javascript getters in the parent as well (show-data = {computedValue})

For those looking for Salesforce learning, CRS Info Solutions provides an extensive Salesforce training program designed to enhance your skills and career opportunities. Explore our Salesforce training in Hyderabad to gain practical, hands-on experience, real-time projects included. Our training covers all essential aspects of Salesforce, ensuring comprehensive learning, providing daily notes, interview questions, certification preparation and job prep guidance. Enroll for Free demo today!

Comments are closed.