Getter and Setter in Salesforce Lightning Web Component (LWC )

 Let’s have a sample LWC component without getter and setter.

 

javascript

import { LightningElement } from 'lwc';

 export default class NoGetterSetterExample extends LightningElement {

    name = 'John'; // Direct assignment

}

 

Html

<template>

    <p>The name is: {name}</p>

</template>

 

 

Output:

The name is: John


 Here we can directly set the value of name to 'John' and {name} will display value ‘John’.

 

Now we see similar example using getter and setter:

 

javascript:

import { LightningElement } from 'lwc';

 export default class GetterSetterExample extends LightningElement {

    _name = ''; // Private property for internal use

 

    // Setter for name

    set name(value) {

        this._name = value.toUpperCase(); // Modify value before assigning it

    }

 

    // Getter for name

    get name() {

        return this._name; // Return modified value

    }

 

    connectedCallback() {

        this.name = 'John'; // Trigger setter

    }

}

 

HTML

<template>

    <p>The name is: {name}</p>

</template>

 

 

Result:

The name is: JOHN

 

Here, the getter and setter add extra control:

 

·         The setter allows you to manipulate the input (e.g., convert the name to uppercase).

·         The getter retrieves the manipulated value when the template requests it.

 

Advantages of Using Getters and Setters

Encapsulation: You can hide the internal details of how data is stored or modified and expose only what is necessary.

Data Transformation: With setters, you can format or validate input data before saving it. With getters, you can format the output or return derived properties.

Reactive Behavior: By using setters, you can trigger additional actions (like updating other properties or firing events) whenever a property is set.

 

Example of a Scenario Without Getters and Setters

In a simpler case where no transformations or logic are needed, you can directly bind properties in the template without getters and setters, as shown in the first example. This might be preferred when you just want to display or store data without any additional processing.

 

Conclusion

While you can achieve a similar result without getters and setters, using them provides more control and flexibility, especially when you need to transform data or implement custom logic.

No comments:

Post a Comment

Async/Await Concept in Javascript/LWC

  Concept of async and await in JavaScript async and await are used in asynchronous programming in JavaScript. They help us write clean...