Sub topic 12
Using a getter and setter pair on a public property
This chapter assumes you can write a small LWC bundle and use @api to expose a property to a parent. It also assumes you know how a getter feeds a template. Here you will learn when a plain @api field is not enough, and how an accessor pair lets a component control the values it accepts.
Why a plain @api field is sometimes not enough
A field marked @api accepts whatever the parent sends. That is fine for a display name. It becomes a problem when the value needs cleaning, for example:
- A parent writes
quantity="5"in markup, so the child receives the string"5", not the number5. - A parent passes
undefinedornullwhile data is still loading. - A parent passes a negative number, but the component only makes sense with zero or more.
- A parent passes an array that the child wants to sort without changing the parent's data.
You could clean the value in every getter that reads it. A better place is the moment the value arrives. A getter and setter pair on the public property gives you that place.
The basic pattern
Here is the pair from the plan, with its template.
// 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);
}
get label() {
return this._quantity === 1 ? '1 item' : `${this._quantity} items`;
}
}<!-- quantityBadge.html -->
<template>
<span class="slds-badge">{label}</span>
</template>Three parts work together:
_quantityis a private field that stores the cleaned value. The leading underscore is a naming convention. It tells readers not to touch the field from outside, and the engine does not enforce it.- The setter runs each time the parent assigns a value. It converts the input, replaces invalid values with
0, and clamps negatives. - The getter returns the stored value. It is the public read side, so the parent and the component itself read
quantitythrough it.
A parent uses the property exactly as it would use a plain @api field:
<!-- parent.html -->
<template>
<c-quantity-badge quantity="-4"></c-quantity-badge>
<c-quantity-badge quantity={cartCount}></c-quantity-badge>
</template>The first badge shows 0 items. The static attribute delivers the string "-4", Number("-4") gives -4, and Math.max(0, -4) gives 0. The second badge shows whatever cartCount is, cleaned the same way.
What happens when the parent sets a value
The sequence below shows one update. The parent changes cartCount, the engine calls the setter, and the child re-renders because the getter-backed field changed.
The re-render happens because the template reads label, and label reads _quantity. Class fields are reactive. When you reassign _quantity to a new value, any template that read it during its last render is scheduled to render again. The setter itself does not need to trigger anything.
Rules for placing @api
Follow these rules, because mistakes are caught at compile time or behave oddly at run time.
- Put
@apion only one accessor of the pair. Decorating both gives a compile error. - Convention is to decorate the first accessor in the file. In the example that is the getter.
- Define both accessors. If you define only a setter, every read of the property returns
undefined. - Do not name the private field the same as the public property.
this.quantity = ...inside the setter would call the setter again and recurse forever.
Comparing the options
| Approach | Where cleaning happens | Good for | Cost |
|---|---|---|---|
| Plain `@api quantity` | Nowhere, or in each getter that reads it | Values used as given | Every reader must handle bad input |
| `@api` getter and setter pair | Once, when the value arrives | Type conversion, defaults, clamping, copying | A private field and a few extra lines |
| Plain `@api` plus a separate derived getter | When the template reads it | Values you want to keep raw, with a formatted view | The raw value stays unchecked |
The second row changes what the property means. Code that reads quantity always sees the cleaned value. In the third row, a getter such as get label() reads the raw property and produces a display string, and the raw value remains available to the component.
Normalizing arrays and objects
Values passed from a parent as objects or arrays are read-only inside the child. You cannot push to an array you received or assign to its properties. A setter that copies the input gives the component its own data to work with.
// tagList.js
import { LightningElement, api } from 'lwc';
export default class TagList extends LightningElement {
_tags = [];
@api
get tags() {
return this._tags;
}
set tags(value) {
const list = Array.isArray(value) ? value : [];
this._tags = [...list].sort((a, b) => a.localeCompare(b));
}
get displayTags() {
return this._tags.map((tag) => ({ key: tag, label: `#${tag}` }));
}
}<!-- tagList.html -->
<template>
<ul>
<template for:each={displayTags} for:item="tag">
<li key={tag.key}>{tag.label}</li>
</template>
</ul>
</template>The spread creates a new plain array, so sorting it does not touch the parent's data. The setter also guards against undefined and non-array values by falling back to an empty list. Be aware that the copy is shallow. If the array holds objects, those objects are still read-only. This example uses strings, so the issue does not arise.
Several properties and ordering
A child often has more than one public property. The engine sets them in the order it processes the parent's attributes, and you should not rely on that order. A setter that reads another public property may see its default value instead of the parent's value.
Suppose a component has min and max and the setter for value clamps between them:
// rangeValue.js
import { LightningElement, api } from 'lwc';
export default class RangeValue extends LightningElement {
_min = 0;
_max = 100;
_value = 0;
@api
get min() {
return this._min;
}
set min(v) {
this._min = Number(v) || 0;
}
@api
get max() {
return this._max;
}
set max(v) {
this._max = Number.isFinite(Number(v)) ? Number(v) : 100;
}
@api
get value() {
return this._value;
}
set value(v) {
this._value = Number(v) || 0;
}
get clampedValue() {
return Math.min(this._max, Math.max(this._min, this._value));
}
}The setters only store raw values. The dependent calculation happens in clampedValue, which runs at render time, after all properties are set. Had value's setter clamped immediately, a parent that sets value before max would get the wrong result.
What to avoid in setters
- Reading other public properties, as shown above.
- Dispatching events. The component may not be connected yet, and the parent is in the middle of its own update.
- Calling Apex or doing other asynchronous work. Use
connectedCallbackor a wire adapter instead. - Throwing for invalid input. A parent typo then breaks rendering. Prefer a default value, and log a warning during development if you need to flag it.
- Expensive computation. The setter runs on every parent assignment, so heavy work repeats on each update.
The setter can also run before the component is connected to the page. At that point the template has not rendered, so there is nothing to query. Store the value and let the template catch up.
Setting the property from inside the component
A component that owns a public property should treat it as input from the parent. Do not assign to the public name from your own methods to change what the parent sees. If the component needs its own working copy, keep it in a private field. If the child wants to tell the parent something changed, dispatch an event and let the parent update its own value.
// quantityStepper.js
import { LightningElement, api } from 'lwc';
export default class QuantityStepper extends LightningElement {
_quantity = 0;
@api
get quantity() {
return this._quantity;
}
set quantity(value) {
this._quantity = Math.max(0, Number(value) || 0);
}
handleIncrease() {
const next = this._quantity + 1;
this.dispatchEvent(new CustomEvent('quantitychange', { detail: next }));
}
}The stepper does not set _quantity itself. It announces the new value and waits for the parent to pass it back through the setter. That keeps data flowing one way: down through properties, up through events.
Common mistakes
- Decorating both the getter and the setter with
@api. The compiler rejects it. - Using the same name for the private field and the public property. This causes recursion.
- Forgetting that attribute values written in markup are strings, so
quantity="5"is"5". Convert in the setter. - Mutating the received array or object. It is read-only, so copy it in the setter first.
- Putting cross-property logic in a setter and depending on the order the parent sets values.
Exercise
A component exposes @api get pageSize() and set pageSize(value). Its setter body is this.pageSize = Math.max(1, Number(value) || 10);. What goes wrong, and how do you fix it so that the value is never below 1, defaults to 10, and works when the parent writes page-size="25"?
Show answer
The setter assigns to this.pageSize, which calls the setter again and recurses until the stack overflows. Store the result in a private field instead: add _pageSize = 10;, write this._pageSize = Math.max(1, Number(value) || 10); in the setter, and return this._pageSize from the getter. The string "25" is converted by Number, so it becomes 25. Note that Number("0") || 10 gives 10, because 0 is falsy, so a value of 0 also falls back to the default of 10.
Exercise
Why is it safer to compute a clamped display value in a getter than inside the setter of the value property when the component also has public min and max properties?
Show answer
The parent may set value before it sets min and max, and the order is not guaranteed. A setter that reads min and max could see their defaults. A getter runs when the template renders, after all properties have been set, so it always uses the final values.