Sub topic 10
Validating and transforming input with @api getters and setters
This chapter assumes you can build a simple Lightning web component, use {property} expressions in a template, and read modern JavaScript (classes, spread syntax, arrow functions). It also assumes you know how to mark a field with @api and set it from a parent template.
Why a plain @api field is not always enough
A plain @api field accepts whatever the parent sends. If the parent passes null, a number where you expected a string, or an array that contains bad entries, your child stores it as is. The template then renders it, or throws an error while rendering.
You can solve this in two ways:
- Check the value everywhere the child uses it.
- Check it once, at the moment it arrives.
An @api getter and setter pair does the second. The setter runs every time the parent assigns a value. It can validate the value, convert it into the form the child needs, or store a defensive copy.
The getter and setter pattern
A public property can be written as a getter and a setter instead of a field. In LWC, you put @api on only one of the two. The decorator applies to the pair, and the convention is to put it on the getter.
// priorityBadge.js (child)
import { LightningElement, api } from 'lwc';
const ALLOWED = ['low', 'normal', 'high'];
export default class PriorityBadge extends LightningElement {
_priority = 'normal';
@api
get priority() {
return this._priority;
}
set priority(value) {
const cleaned = typeof value === 'string' ? value.trim().toLowerCase() : '';
this._priority = ALLOWED.includes(cleaned) ? cleaned : 'normal';
}
}<!-- priorityBadge.html (child) -->
<template>
<span class="badge">{priority}</span>
</template>Here is what happens when a parent writes <c-priority-badge priority=" HIGH "></c-priority-badge>:
- The framework assigns the attribute value to the public property
priority. - The setter runs. It trims the text and converts it to lower case, which gives
high. highis in the allowed list, so it is stored in_priority.- The template reads
prioritythrough the getter and showshigh.
If the parent sends urgent, null, or 42, the child falls back to normal.
The backing field
The setter does not store the value on the property itself. It stores it in a separate private field. This field is called the backing field, and the usual name is the public name with a leading underscore, such as _priority.
If the setter assigned to this.priority, it would call itself again, and the code would loop until the stack overflows.
// Wrong: the setter calls itself forever.
set priority(value) {
this.priority = value;
}Why the getter is required
A setter alone is not enough. If you define set priority without a getter, reading this.priority returns undefined, and the template shows nothing. Always define both. The getter can return the backing field unchanged, or it can compute something from it.
Where to put the decorator
Put @api on the getter or on the setter, but not on both. The following code fails to compile:
@api
get priority() { return this._priority; }
@api
set priority(value) { this._priority = value; }The compiler reports that a getter and setter pair can have only one @api decorator. Place it on whichever comes first, which by convention is the getter.
Transforming input
A setter does not only reject bad values. It can also change the shape of the value so the rest of the component works with a form that suits it.
Common transformations include:
- Normalizing text (trim, lower case).
- Converting a string to a number or a date.
- Turning a comma-separated string into an array.
- Adding default fields to each object in an array.
// tagList.js (child)
import { LightningElement, api } from 'lwc';
export default class TagList extends LightningElement {
_tags = [];
@api
get tags() {
return this._tags;
}
set tags(value) {
const raw = Array.isArray(value)
? value
: typeof value === 'string'
? value.split(',')
: [];
this._tags = raw
.map((tag) => String(tag).trim())
.filter((tag) => tag.length > 0);
}
get tagCount() {
return this._tags.length;
}
}<!-- tagList.html (child) -->
<template>
<p>{tagCount} tags</p>
<ul>
<template for:each={tags} for:item="tag">
<li key={tag}>{tag}</li>
</template>
</ul>
</template>A parent can now send either tags="lwc, salesforce, ,docs" or an array. In both cases the child ends up with a clean array of non-empty strings.
Note that this setter builds a new array with map and filter. It never changes the array that the parent passed in.
Copying objects and arrays in the setter
Values passed from a parent are read-only in the child. If the child tries to push to an array or change a field on an object it received, LWC throws an error. This is the one-way data flow rule from earlier in the tutorial.
A setter is the best place to make a copy, because it is the single entry point for the value.
// taskList.js (child)
import { LightningElement, api } from 'lwc';
export default class TaskList extends LightningElement {
_tasks = [];
@api
get tasks() {
return this._tasks;
}
set tasks(value) {
// Copy the incoming array: values from a parent are read-only in the child.
this._tasks = Array.isArray(value) ? [...value] : [];
}
handleSortByName() {
this._tasks = [...this._tasks].sort((a, b) => a.name.localeCompare(b.name));
}
}The spread syntax [...value] creates a new array, so the child can reorder or filter its own list. This is a shallow copy. The array is new, but the objects inside it are still the parent's objects, and they are still read-only. If the child must change a field on one of those objects, copy that object too:
set tasks(value) {
this._tasks = Array.isArray(value)
? value.map((task) => ({ ...task, done: Boolean(task.done) }))
: [];
}The spread { ...task } creates a new object for each item, so the child owns every level it needs to change.
When the setter runs
The setter runs in these situations:
- When the parent first sets the property, before the child is connected to the page.
- Every time the parent assigns a new value to that property afterwards.
The setter does not run when the parent mutates an object or array it already passed. The parent's own reactivity decides whether the child sees a change, and that depends on how the parent updates its data. If the parent wants the child to re-run the setter, it should assign a new object or array.
// taskBoard.js (parent)
addTask(task) {
// Assigning a new array triggers the child's setter again.
this.tasks = [...this.tasks, task];
}Order of setters
When a parent sets several properties on one child, the order in which the setters run is not something you should rely on. If one setter needs the value from another, do not read the other property inside the setter. Store the raw values and do the combined work later, for example in a getter or in renderedCallback.
// priceTag.js (child)
import { LightningElement, api } from 'lwc';
export default class PriceTag extends LightningElement {
_amount = 0;
_currency = 'USD';
@api
get amount() {
return this._amount;
}
set amount(value) {
const number = Number(value);
this._amount = Number.isFinite(number) ? number : 0;
}
@api
get currency() {
return this._currency;
}
set currency(value) {
this._currency = typeof value === 'string' && value ? value.toUpperCase() : 'USD';
}
get formatted() {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: this._currency
}).format(this._amount);
}
}The formatted getter reads both backing fields when the template renders, so it does not matter which setter ran first.
Decision flow
Gotchas
- Dropping the getter. A setter with no getter makes the property read as
undefined. - Using the same name for the field and the property.
priorityas both a field and an accessor is a name clash. Use_priorityfor the field. - Decorating both accessors. Only one of the two can carry
@api. - Throwing errors in the setter. An exception during assignment breaks the parent's rendering. Prefer a safe default, and log a warning with
console.warnwhile developing if the input is clearly wrong. - Heavy work in the setter. The setter runs on every assignment. Keep it cheap, and do expensive calculations in a getter that is read only when needed.
- Assuming the child is connected. When the setter first runs, the child has not rendered yet. Do not call
this.template.querySelectorinside a setter, because the elements do not exist. - Expecting a setter to run on mutation. Changing
this.tasks.push(x)in the parent does not assign the property, so the child's setter does not run.
Setter or getter: which should transform?
| Need | Better place | Reason |
|---|---|---|
| Reject or fix bad input | Setter | The check runs once, when the value arrives |
| Copy an array or object | Setter | One entry point, and the copy is stable |
| Format for display (currency, dates) | Getter | Depends on several values and is cheap to compute |
| Combine two public properties | Getter | Avoids relying on setter order |
| Query the rendered DOM | `renderedCallback` | The DOM does not exist when setters run |
Exercise
A child exposes @api get items() and set items(value). The setter does this.items = Array.isArray(value) ? [...value] : [];. What happens when the parent assigns a new array, and how do you fix the code?
Show answer
The setter assigns to this.items, which calls the setter again, so it recurses until the stack overflows. Store the value in a backing field instead, such as this._items = Array.isArray(value) ? [...value] : [];, and make the getter return this._items.
Exercise
A parent calls this.tasks.push(newTask) on an array it already passed to a child whose tasks setter copies the array. Why does the child not show the new task, and what should the parent do?
Show answer
Pushing mutates the existing array and never assigns the property, so the child's setter does not run and the child keeps its earlier copy. The parent should assign a new array, for example this.tasks = [...this.tasks, newTask];, which runs the setter again.