Sub topic 12
Using a Getter and Setter Pair on a Public Property
This chapter assumes you can build a basic Lightning Web Component bundle and that you know how @api exposes a property to a parent. It also assumes you are comfortable with JavaScript classes, getters, and template literals.
Why a plain @api field is sometimes not enough
An @api field accepts whatever the parent sends. A parent can pass a string, a negative number, or undefined, and the child stores it unchanged. If the child needs clean data, such as a number that is never below zero, you have two choices. You can check the value every time you use it, or you can clean it once, when it arrives.
A getter and setter pair does the second. The setter runs each time the parent assigns a value. It stores a cleaned copy in a private field. The getter returns that private field.
The pattern
// quantityBadge.js
import { LightningElement, api } from 'lwc';
export default class QuantityBadge extends LightningElement {
_quantity = 0;
@api
get quantity() {
return this._quantity;
}
set quantity(value) {
this._quantity = Math.max(0, Number(value) || 0);
}
}Three parts matter here:
_quantityis the private backing field. The leading underscore is a naming convention that tells readers not to touch it from outside. The parent cannot reach it, because it has no@api.- The setter normalizes the input.
Number(value) || 0turnsundefined,null, empty strings, andNaNinto0.Math.max(0, ...)removes negatives. @apigoes on only one accessor of the pair. LWC applies it to the property as a whole. Putting@apion both the getter and the setter is a compile error.
How the data flows
The parent uses the property the same way it would use a plain @api field. It does not know a setter exists:
<!-- parent.html -->
<template>
<c-quantity-badge quantity={selectedQuantity}></c-quantity-badge>
</template>If selectedQuantity is -5, the child stores 0. If it is the string "7", the child stores the number 7.
Using the value in the child template
The child's template binds to the public property as usual:
<!-- quantityBadge.html -->
<template>
<span class="badge">Qty: {quantity}</span>
</template>The template reads quantity, which calls the getter. Because the setter writes to _quantity, a class field, and the template reads it through the getter, a new value from the parent triggers a re-render.
Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `@api` on both getter and setter | The compiler rejects the component | Put `@api` on the first accessor only |
| Setter stores into the same name, such as `this.quantity = value` | Infinite recursion and a stack overflow | Store into a differently named private field |
| Getter with no setter | Parent assignments have no effect, and the framework may warn | Add the setter, or use a read-only getter on purpose |
| Setter that reads other `@api` properties | Result depends on the order the parent sets them | Do the combined work in a getter, or in `connectedCallback` |
| Modifying the value inside the child after it is set | The child's data can drift from the parent's | Treat public properties as read-only, and copy to a private field |
The second mistake is the easiest to make. The setter name and the property name are the same, so this.quantity = value calls the setter again, which calls itself. The private field is what breaks the loop.
Order of assignment
LWC may set public properties one at a time, and the order is not something to rely on. A setter should therefore work from its own incoming value only. If two properties together decide an outcome, compute that outcome in a getter, which runs at render time after all values have arrived.
Summary
A getter and setter pair on a public property lets a component control what it accepts. The setter validates and stores the value in a private field. The getter returns it. Put @api on one accessor only, and never assign to the public name inside its own setter.
Exercise
A component declares @api get label() { return this._label; } and set label(value) { this.label = value.trim(); }. What goes wrong when a parent sets label, and how do you fix it?
Show answer
The setter assigns to this.label, which calls the same setter again, so it recurses until the stack overflows. Store the result in the private field instead: this._label = value.trim();. It is also worth guarding against a missing value, for example this._label = value ? value.trim() : '';, because undefined.trim() throws.
Exercise
Modify the QuantityBadge setter so that values above 99 are capped at 99. Write the one line you would change.
Show answer
this._quantity = Math.min(99, Math.max(0, Number(value) || 0));