Sub topic 9
Validating input with @api getters and setters
This chapter assumes you can write a Lightning web component with a JavaScript class and an HTML template. You should also know how a parent passes values to a child through attributes, and the difference between reassigning a field and mutating an object. Earlier chapters covered @api on plain fields. This chapter covers @api on a getter and setter pair, which lets the child check or reshape a value before it uses it.
Why a plain @api field is not always enough
An @api field stores whatever the parent sends. That is fine for simple cases. It becomes a problem when the value needs cleanup.
Attributes written in a template as plain text always arrive as strings. If a parent writes amount="12.5", the child receives the string "12.5", not the number 12.5. A parent that binds an expression such as amount={total} might send a number, undefined, null, or a string, depending on the data.
With a plain field, the child has to defend against all of these every time it reads the value. A getter and setter pair moves that work to one place, the moment the value arrives.
The getter and setter pattern
A getter is a method that runs when code reads a property. A setter is a method that runs when code assigns to it. When you put @api on a property that has both, the parent sees one public property. The child runs your code on every read and write.
import { LightningElement, api } from 'lwc';
export default class PriceTag extends LightningElement {
_amount = 0;
@api
get amount() {
return this._amount;
}
set amount(value) {
this._amount = Number(value) || 0;
}
get formatted() {
return this._amount.toFixed(2);
}
}Three parts matter here.
- The private backing field.
_amountholds the real value. The leading underscore is a naming convention that says "internal". It is not enforced, and it is not@api, so the parent cannot set it. - The setter. It converts the incoming value with
Number(value). If the result isNaN(not a number) or0, the|| 0falls back to0. A parent that sends"abc"orundefinedends up with0. - The getter. It returns the stored, cleaned value. Anyone reading
amountgets the normalized number, never the raw input.
The separate formatted getter has no @api. It is a private computed value for the template, for example <p>${ formatted }</p> written as {formatted}.
Pairing with a template
A parent can then pass messy input:
<template>
<c-price-tag amount="12.5"></c-price-tag>
<c-price-tag amount="oops"></c-price-tag>
</template>The first tag shows 12.50. The second shows 0.00. The child never holds an invalid value.
Put @api on only one of the pair
Place @api on either the getter or the setter, not both. The decorator applies to the property as a whole. The platform reports an error at compile time if both accessors carry it.
By convention, put it on the first accessor in the file. In the example above that is the getter. Keep the two accessors next to each other so a reader sees them as one unit.
What triggers a rerender with accessors
A plain field is reactive because the engine watches the field. With a getter and setter, the reactive piece is the private backing field you read in the template.
In PriceTag, the template reads formatted, and formatted reads _amount. When the setter assigns a new value to _amount, the engine sees that a field used during rendering changed, and it rerenders. You do not need to do anything extra.
This has a consequence. If the setter ignores a value and leaves _amount as it was, nothing changed, so there is no rerender. If a parent sends "0" and _amount is already 0, the assigned value equals the old value, and no rerender happens.
Common validation tasks
The setter is the right place for a few recurring jobs.
Converting types
Convert strings to numbers or booleans. A boolean attribute written as expanded in HTML arrives as true, but a parent binding expanded={flag} might send other types.
import { LightningElement, api } from 'lwc';
export default class Panel extends LightningElement {
_expanded = false;
@api
get expanded() {
return this._expanded;
}
set expanded(value) {
this._expanded = value === true || value === 'true';
}
}Clamping to a range
Restrict a value to allowed bounds.
import { LightningElement, api } from 'lwc';
export default class RatingBar extends LightningElement {
_rating = 0;
@api
get rating() {
return this._rating;
}
set rating(value) {
const n = Number(value);
if (Number.isNaN(n)) {
this._rating = 0;
} else {
this._rating = Math.min(5, Math.max(0, Math.round(n)));
}
}
get stars() {
return '★'.repeat(this._rating) + '☆'.repeat(5 - this._rating);
}
}A rating of 9 becomes 5. A rating of -3 becomes 0. A rating of 3.6 becomes 4.
Restricting to allowed values
Accept only known options and fall back to a default.
import { LightningElement, api } from 'lwc';
const SIZES = ['small', 'medium', 'large'];
const DEFAULT_SIZE = 'medium';
export default class Badge extends LightningElement {
_size = DEFAULT_SIZE;
@api
get size() {
return this._size;
}
set size(value) {
this._size = SIZES.includes(value) ? value : DEFAULT_SIZE;
}
get cssClass() {
return `badge badge-${this._size}`;
}
}Setters run before the component is connected
The engine can call a setter before the component is connected to the page. The parent sets attributes while it creates the child. At that point:
- The template has not rendered, so
this.template.querySelector(...)finds nothing. - Other
@apiproperties may not be set yet. Their order is not guaranteed.
So keep the setter simple. Store a cleaned value. Do not query the DOM, and do not depend on another public property having arrived. If one value depends on another, compute the combination in a getter that the template reads, or in renderedCallback once everything is set.
import { LightningElement, api } from 'lwc';
export default class RangeLabel extends LightningElement {
_min = 0;
_max = 10;
@api
get min() {
return this._min;
}
set min(value) {
this._min = Number(value) || 0;
}
@api
get max() {
return this._max;
}
set max(value) {
this._max = Number(value) || 0;
}
get label() {
return this._min <= this._max
? `${this._min} to ${this._max}`
: 'Invalid range';
}
}Here neither setter checks the other. The label getter combines them when the template reads it, so the result is right whichever one arrives first.
Mutating the value inside a setter
A setter often stores the incoming value. If that value is an object or array owned by the parent, the stored value is the parent's object. The engine makes public properties read-only from the child's point of view, so the child cannot change the object it received. Attempting to change it fails.
If the child needs its own editable copy, make one in the setter:
import { LightningElement, api } from 'lwc';
export default class TagList extends LightningElement {
_tags = [];
@api
get tags() {
return this._tags;
}
set tags(value) {
this._tags = Array.isArray(value) ? [...value] : [];
}
addTag(name) {
this._tags = [...this._tags, name];
}
}The spread copy gives TagList an array it owns, and addTag reassigns _tags, which triggers a rerender. The parent's array is untouched. A value that is not an array becomes an empty list instead of causing an error later.
Getters that return derived values
A public getter does not have to return a stored field. It can compute a result. Without a setter, the property is read-only to the parent.
import { LightningElement, api } from 'lwc';
export default class Cart extends LightningElement {
items = [
{ name: 'Pen', price: 2 },
{ name: 'Notebook', price: 5 }
];
@api
get total() {
return this.items.reduce((sum, item) => sum + item.price, 0);
}
}A parent can read total through a reference to the element, but it cannot assign to it. Use this when you want to expose a result and not accept input.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Compile error about duplicate decorators | `@api` on both getter and setter | Keep it on one accessor |
| Property reads as `undefined` | Setter defined without a getter | Add a getter that returns the backing field |
| Infinite loop or stack overflow | Getter or setter uses the public name instead of the backing field | Store in `_name`, not `name` |
| String `"5"` appears where a number is expected | Raw attribute stored without conversion | Convert with `Number(value)` in the setter |
| Setter throws on `querySelector` result | DOM not rendered yet | Move DOM work to `renderedCallback` |
| Value does not update after the parent changes it | Setter never assigns to a field the template reads | Assign the cleaned value to a backing field used in rendering |
The stack overflow case is common. Inside the setter for amount, writing this.amount = ... calls the setter again, forever. Always write to the underscore field.
How the pieces fit
Choosing accessors or a plain field
Use a plain @api field when any value the parent sends is acceptable and the child uses it as is. Use a getter and setter pair when you need to do one of these:
- Convert the type, such as string to number.
- Clamp or restrict the value.
- Copy the incoming object or array.
- Run a small side effect each time the value changes, such as recording that it changed.
Keep setters short. If validation grows complicated, move it into a helper function and call that function from the setter.
Exercise
A child component has @api get level() returning this._level, and a setter that contains this.level = Number(value);. A parent sets level="3". What happens, and how do you fix it?
Show answer
The setter assigns to this.level, which is the public property itself. That calls the same setter again, which assigns again, and the call stack overflows. Fix it by assigning to the backing field: this._level = Number(value);.
Exercise
Write the setter for a public quantity property that must be a whole number from 1 to 99. Anything that is not a number should become 1. Name the backing field _quantity.
Show answer
set quantity(value) {
const n = Math.round(Number(value));
this.quantity = Number.isNaN(n) ? 1 : Math.min(99, Math.max(1, n));
}
The setter converts to a number and rounds it. It falls back to 1 when the result is NaN. Otherwise it clamps the value between 1 and 99. The getter returns `this.quantity, and @api` goes on one of the two accessors only.