Sub topic 10
Validating and transforming input with @api getters and setters
This chapter assumes you can build a basic Lightning web component and that you know how a parent sets a child's @api property from its template. It also assumes you are comfortable with classes, spread syntax, and the idea that values a child receives from a parent are read-only.
Why a plain @api field is not always enough
A field marked with @api accepts whatever the parent sends. That is fine for a heading string. It causes trouble when the child needs to do any of these:
- Reject bad input, such as a
nullwhere it expects an array. - Normalize a value, such as trimming text or converting it to upper case.
- Copy an object or array so the child can change its own version.
- Run logic whenever the parent changes the value.
An @api getter and setter pair handles all of these. The setter runs each time the parent assigns the property, so it is the right place to check or reshape the value.
The pattern
Put @api on the getter only, and keep the real value in a private field. Use an underscore prefix by convention.
// 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 setter does two jobs here:
- Validation. If the parent passes something that is not an array, the child falls back to an empty list instead of failing later in the template or in
sort. - Copying. The spread syntax creates a new array. The child can then reorder
_taskswithout touching the parent's data.
The parent uses the property as usual:
<!-- taskBoard.html (parent) -->
<template>
<c-task-list tasks={tasks}></c-task-list>
</template>How the flow works
The setter runs on the first assignment and again each time the parent supplies a new value. If the parent changes its property to a new array, the setter runs again and the child gets a fresh copy.
Rules to follow
- Decorate only one accessor. Put
@apion either the getter or the setter, not both. By convention it goes on the first one in the file. LWC applies it to the pair. - Always define a getter. If the setter has no getter, the parent cannot read the value back, and the property is hard to debug.
- Return the private field from the getter. Do not compute a new object each time, or the template may re-render more than needed.
- Do not read other
@apiproperties inside a setter. The parent may set properties in any order, so another property may not have a value yet. Do dependent work in a getter or inrenderedCallbackinstead.
Transforming a value
A setter can also change the value's form. This example keeps a priority in a known format:
// taskCard.js (child)
import { LightningElement, api } from 'lwc';
const ALLOWED = ['low', 'normal', 'high'];
export default class TaskCard extends LightningElement {
_priority = 'normal';
@api
get priority() {
return this._priority;
}
set priority(value) {
const cleaned = String(value ?? '').trim().toLowerCase();
this._priority = ALLOWED.includes(cleaned) ? cleaned : 'normal';
}
}A parent that writes priority=" HIGH " ends up with high. An unknown value such as urgent falls back to normal.
Exercise
A child has @api on both a getter and its setter for the items property, and the setter stores value directly in _items. Name two problems with this code, and say how to fix each.
Show answer
First, @api should appear on only one accessor, so remove it from the second. Second, storing value directly means the child holds the parent's read-only array, so sorting or editing it fails. Copy it in the setter, for example this._items = Array.isArray(value) ? [...value] : [];, which also guards against non-array input.