Sub topic 9
Validating input with @api getters and setters
This chapter assumes you can write a basic Lightning web component and know how @api exposes a public property. You should also know that a parent sets a child's properties from its template. Here you will see how to intercept the values a parent passes in, so the child can validate or transform them before use.
Why a plain @api field is not always enough
A field decorated with @api accepts whatever the parent gives it. A parent can pass a string where you expect a number, or pass nothing at all. HTML attributes in a template are often strings, so amount="12.5" arrives as the text "12.5".
If the child calls .toFixed(2) on that string, it throws an error. A getter and setter pair lets you clean up the value at the point where it enters the component.
The getter and setter pattern
The pattern has three parts:
- A private field, by convention prefixed with an underscore, that stores the cleaned value.
- A setter that receives the raw value, normalizes it, and stores it in the private field.
- A getter that returns the stored value.
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);
}
}The setter runs each time a parent assigns amount. Number(value) || 0 converts text such as "12.5" to a number. It also turns undefined, null, and non-numeric text such as "abc" into 0, so formatted always works on a number.
<template>
<p>Price: {formatted}</p>
</template>The template reads formatted, a plain getter with no @api. It stays private to the component.
Decorate only one accessor
Put @api on either the getter or the setter, but not both. LWC treats the pair as one public property. Decorating both causes a compile error. By convention, place it on the getter, which is the first one declared.
The private field _amount is not public. A parent cannot reach it, and it has no decorator.
Reactivity still works
The private field _amount is a normal class field, so it is reactive. When the setter reassigns it, any template expression that reads _amount, directly or through a getter like formatted, rerenders. You do not need extra code to trigger the update.
Using the component
A parent sets the property like any other public property.
<template>
<c-price-tag amount="12.5"></c-price-tag>
</template>The setter receives the string "12.5" and stores the number 12.5. The tag displays 12.50.
Other things a setter can do
A setter is ordinary code, so you can use it for more than type conversion:
- Clamp a number into a range, for example
Math.min(Math.max(n, 0), 100). - Trim whitespace from text.
- Fall back to a default when the value is missing.
- Warn in the console when a value is invalid.
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);
this._rating = Number.isNaN(n) ? 0 : Math.min(Math.max(n, 0), 5);
}
}Common errors
- Using the same name for the field and the accessor. If both are called
amount, the setter calls itself forever. Use a different name such as_amount. - Decorating both accessors. Use
@apionce per pair. - Defining only a setter. The property then reads as
undefined. Provide a getter too. - Assuming the setter runs before the first render. It runs when the parent assigns a value. If the parent never assigns one, the setter never runs and the private field keeps its initial value. Give it a sensible default.
Exercise
A parent passes rating="9" to the RatingBar component above. What value does the getter return, and why?
Show answer
It returns 5. The setter converts "9" to the number 9, which is not NaN, then clamps it with Math.min(Math.max(9, 0), 5), giving 5.
Exercise
Why should the private field be named _amount rather than amount when the public accessor is amount?
Show answer
The accessor and the field would share one name. The setter would then assign to itself and recurse forever. A different name keeps the stored value separate from the accessor.