Sub topic 12
Common pitfalls and how to avoid them
This chapter assumes you know how plain fields, @track, and @api behave in a Lightning web component. It collects the mistakes that most often leave a screen stale or throw errors, and gives the fix for each.
Pitfall 1: Mutating a plain field instead of reassigning it
A plain field rerenders the component when you assign a new value to it. Changing something inside the value does not count as an assignment. Arrays are the most common case.
import { LightningElement } from 'lwc';
export default class TaskList extends LightningElement {
tasks = ['Write tests'];
addBroken() {
// The array changes, but the field is not reassigned: no rerender.
this.tasks.push('Deploy');
}
addFixed() {
// A new array is assigned to the field: the template refreshes.
this.tasks = [...this.tasks, 'Deploy'];
}
}The same applies to objects. Write this.profile = { ...this.profile, name: 'Grace' } instead of this.profile.name = 'Grace'. Use @track only when you need nested mutation to be observed. Reassignment works in every other case and is easier to reason about.
Pitfall 2: Expecting @track to observe everything
@track observes changes inside plain objects and arrays. It does not observe other kinds of values, such as instances of your own classes, a Date, a Map, or a Set. Changing the inside of one of these does not rerender the component. Reassign the field with a new value instead.
Pitfall 3: A child changing its own @api property
A parent owns the value of a child's @api property. If the child assigns to it, the child gets a read-only error, and the child's version could drift from the parent's anyway. Copy the value into a private field and report changes upward with an event.
import { LightningElement, api } from 'lwc';
export default class QuantityPicker extends LightningElement {
@api startAt = 1;
current;
connectedCallback() {
this.current = this.startAt;
}
increase() {
this.current += 1;
this.dispatchEvent(new CustomEvent('change', { detail: this.current }));
}
}The parent listens for change and decides what to store. This copy is made once, when the component connects. If the parent later changes startAt, current does not follow. When the child must follow the parent, use an @api setter that updates the private field, as in the next pitfall.
Pitfall 4: Decorating both halves of a getter and setter
For an accessor pair, put @api on only one of the two. The decorator applies to the whole property. Decorating both halves causes a compile error.
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;
}
}Store the value in a separate private field such as _amount. If the setter assigns to this.amount, it calls itself forever.
Pitfall 5: Calling a child method that is not there yet
this.template.querySelector('c-search-box') returns null if the child has not rendered, for example when it sits inside an if:true block that is currently false. Calling a method on null throws an error. Check the result first, as in the earlier SearchPage example. Call child methods from event handlers, not from constructor or early in connectedCallback, when children may not exist yet.
Pitfall 6: Naming mismatches in the parent template
In JavaScript the property is startAt. In the parent's HTML it is start-at. Writing startAt="3" in the template silently sets nothing useful. Always convert camelCase names to kebab-case in markup.
A quick debugging path
When the screen does not update, work through the questions in this diagram.
Summary table
| Symptom | Likely cause | Fix |
|---|---|---|
| List does not grow after `push` | Mutation of a plain field | Reassign a new array |
| Nested change ignored with `@track` | Value is not a plain object or array | Reassign the field |
| Read-only error in the child | Child assigns to its `@api` property | Use a private copy and an event |
| Compile error on accessors | `@api` on both getter and setter | Decorate one only |
| `null` error calling a child method | Child not rendered yet | Guard the lookup |
Exercise
A component declares items = [] as a plain field and runs this.items.push(newItem) in a click handler. The template iterates over items, but the list never changes. Give two ways to fix it and say which you would choose.
Show answer
Fix one: reassign the field with this.items = [...this.items, newItem]. Fix two: declare the field as @track items = [], so the push is observed. Choose the reassignment. It works without a decorator and behaves the same for every kind of value.
Exercise
A child component has @api label and runs this.label = 'Done' in a handler. What happens, and what should the child do instead?
Show answer
The assignment fails because a child cannot modify its own @api property, which the parent owns. The child should keep the display text in a private field, or dispatch a custom event so the parent changes the value it passes in.