Use Getters and Setters to Modify Data
To execute logic each time a public property is set, write a custom setter.
If you write a setter for a public property, you must also write a getter. Annotate either the getter or the setter with @api, but not both.
For consistency, the examples in this guide and in the lwc-recipes repo annotate the getter and present the getter before the setter.
To hold the property value inside the getter and setter, use a field. This example uses the _uppercaseItemName property, which is prefixed with an underscore to indicate that the property is private.
This sample <c-todo-item> component converts a string to uppercase.
1
2<template> {itemName} </template>
The property value is provided to the template via the getter.
1// todoItem.js
2import { LightningElement, api } from "lwc";
3export default class TodoItem extends LightningElement {
4 _uppercaseItemName;
5
6 @api
7 get itemName() {
8 return this._uppercaseItemName;
9 }
10
11 set itemName(value) {
12 this._uppercaseItemName = value.toUpperCase();
13 }
14}
You can also handle errors in your getter with a try-catch block.
1// todoItem.js
2import { LightningElement, api } from "lwc";
3export default class TodoItem extends LightningElement {
4 _uppercaseItemName;
5
6 @api
7 get itemName() {
8 try {
9 return this._uppercaseItemName;
10 } catch (e) {
11 return "";
12 }
13 }
14
15 set itemName(value) {
16 this._uppercaseItemName = value.toUpperCase();
17 }
18}
For another example of using a getter and setter, see the apiSetterGetter and todoList components in the lwc-recipes sample repo.
See Also
This release is in preview. Features described here don't become generally available until the latest general availability date that Salesforce announces for this release. Before then, and where features are noted as beta, pilot, or developer preview, we can't guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features.