Sub topic 14
Common pitfalls and how to debug them
This chapter collects the mistakes that most often break data passing from a parent Lightning web component to a child. It assumes you can already create a component, mark a field with @api, and bind values in a template. Each pitfall below lists the symptom, the cause, and a fix.
A debugging mindset
Most data-passing bugs fall into three groups.
- The value never reaches the child. The cause is usually a naming or binding mistake.
- The value reaches the child but cannot be changed there. The cause is the read-only rule for values from a parent.
- The value reaches the child but the screen does not update. The cause is usually a mutation that the framework cannot see, or a setter that does not store what it receives.
Decide which group you are in before you change any code. The group tells you where to look.
Pitfall 1: forgetting `@api`
A field without @api is private. The parent can write the attribute in its markup, but the child never receives the value, and nothing warns you.
// taskCard.js (child), broken
import { LightningElement } from 'lwc';
export default class TaskCard extends LightningElement {
heading; // private: the parent cannot set it
}The fix is to add the decorator.
// taskCard.js (child), fixed
import { LightningElement, api } from 'lwc';
export default class TaskCard extends LightningElement {
@api heading;
}Also check the import. Using @api without importing api from lwc is a compile error, which is easier to find than the silent failure above.
Pitfall 2: attribute names written in camelCase
JavaScript property names use camelCase. HTML attribute names in the parent template use kebab-case. A property called dueDate must be set with due-date.
<!-- Broken: the attribute name does not match the property -->
<c-task-card dueDate="2026-12-01"></c-task-card>
<!-- Fixed -->
<c-task-card due-date="2026-12-01"></c-task-card>When a value is missing in the child, compare the property name letter by letter with the attribute name. Every capital letter in the property becomes a hyphen and a lowercase letter in the attribute.
A related restriction applies to the property name itself. Do not start an @api property name with data, aria or on, and do not use names that clash with standard HTML attributes, such as title or hidden, unless you want that meaning. Names that start with on look like event handlers, and data and aria prefixes are reserved for HTML attributes.
Pitfall 3: quotes where braces belong
A quoted value is a literal string. Braces bind to a value in the parent's class.
<!-- The child receives the text "nextHeading" -->
<c-task-card heading="nextHeading"></c-task-card>
<!-- The child receives the value of nextHeading from the parent -->
<c-task-card heading={nextHeading}></c-task-card>Do not put quotes around the braces. Write heading={nextHeading}, not heading="{nextHeading}".
Pitfall 4: booleans that default to true
An HTML attribute is either present or absent. If you write disabled="false", the attribute is present, and the child receives the string "false", which is truthy in JavaScript.
For this reason, give every boolean public property a default of false.
// taskCard.js (child)
import { LightningElement, api } from 'lwc';
export default class TaskCard extends LightningElement {
@api isUrgent = false;
}<!-- The parent turns the flag on by writing the attribute with no value -->
<c-task-card is-urgent></c-task-card>
<!-- Or binds it to a real boolean from the parent's class -->
<c-task-card is-urgent={taskIsUrgent}></c-task-card>A property that defaults to true has a worse problem. The parent cannot turn it off by omitting the attribute, because omitting it leaves the default in place. Design the property so that "off" is the default state, and name it for the thing that gets turned on.
Do not write is-urgent="false" to turn a flag off. Bind a boolean value with braces or leave the attribute out.
Pitfall 5: changing a value the child received
Values that a parent passes in are read-only inside the child. If the child assigns to the property, the framework reports an error in the browser console, and the assignment is not allowed to succeed.
// Broken: assigning to an @api property inside the child
handleReset() {
this.heading = ''; // error: the parent owns this value
}This applies to objects and arrays too, which makes it harder to notice. Code such as this.tasks.push(item) or this.task.done = true changes the parent's data in place, and the framework blocks it.
// Broken: mutating a received array
handleAdd(item) {
this.tasks.push(item); // error: the array belongs to the parent
}There are two correct responses, depending on what you need.
- If the child needs its own working copy, copy the value in a setter and change the copy. The
TaskListexample from the earlier chapter does this. - If the child wants the parent to change its data, send a custom event and let the parent update the value. The new value then flows down again.
// taskList.js (child)
import { LightningElement, api } from 'lwc';
export default class TaskList extends LightningElement {
_tasks = [];
@api
get tasks() {
return this._tasks;
}
set tasks(value) {
this._tasks = Array.isArray(value) ? [...value] : [];
}
handleAdd() {
// Change the private copy, never the received array
this._tasks = [...this._tasks, { id: 'new', name: 'New task' }];
}
}Keep in mind that a copy made with spread syntax is shallow. The array is new, but the objects inside it are still the parent's objects. To change an item, replace it with a new object, for example { ...item, done: true }.
Pitfall 6: a getter without a setter, or the reverse
When you use an @api getter and setter, decorate only the first accessor in the source. LWC applies the decorator to the pair. Putting @api on both is an error.
Two other mistakes are common.
- The setter validates the value but never stores it. The getter then returns the old value, and the screen never changes.
- The setter reads another
@apiproperty that the parent has not set yet. Parents set properties in the order the attributes appear, and the first call can come before the others. Do not assume the other property is available inside a setter. Store the raw value, and do the combined work in a getter that the template reads.
// priorityBadge.js (child)
import { LightningElement, api } from 'lwc';
export default class PriorityBadge extends LightningElement {
_level = 'normal';
@api
get level() {
return this._level;
}
set level(value) {
const allowed = ['low', 'normal', 'high'];
this._level = allowed.includes(value) ? value : 'normal';
}
get badgeClass() {
return `badge badge-${this._level}`;
}
}Pitfall 7: reading `@api` values too early
The constructor runs before the parent sets any properties, so public properties are not available there. Read them in connectedCallback() or later, or use a setter to react at the moment each value arrives.
import { LightningElement, api } from 'lwc';
export default class TaskCard extends LightningElement {
@api heading;
constructor() {
super();
console.log(this.heading); // undefined
}
connectedCallback() {
console.log(this.heading); // the value from the parent
}
}A value that arrives later, for example from a server call in the parent, can be undefined at first. The child should handle that state. Use a default, or hide the content with if:true or lwc:if until the value exists.
Pitfall 8: list problems with `for:each`
Three mistakes appear again and again when you render children from a list.
- The
keyis missing, or it is not on the outermost element inside the loop. The compiler reports an error for a missing key. - The key is an array index. Keys must be unique and stable, so use an id from the data. An index key causes wrong state when items are reordered or removed.
- The binding is written against the wrong name. The name after
for:itemis the variable you use inside the loop, sotask.nameworks only if you wrotefor:item="task".
<template for:each={tasks} for:item="task">
<c-task-card
key={task.id}
heading={task.name}
priority={task.priority}>
</c-task-card>
</template>Pitfall 9: a method call on a child that is not ready
A parent that calls a child's @api method must find the child first. this.template.querySelector('c-search-box') returns null if the child has not rendered yet, or if a condition hides it. Calling a method on null throws a TypeError.
handleShowSearch() {
const box = this.template.querySelector('c-search-box');
if (box) {
box.focus();
}
}Run such calls from an event handler or from renderedCallback(), not from connectedCallback(), because the child elements do not exist yet in connectedCallback(). Also remember that the selector uses the kebab-case tag name, c-search-box, not the class name.
Debugging techniques
Work through the problem in this order.
- Log the value in the child. Put
console.log(JSON.stringify(this.tasks))in a setter or inrenderedCallback(). Plainconsole.logof a received object may show a proxy, which is harder to read, soJSON.stringifygives you a clearer view. - Inspect the rendered element in the browser developer tools. If the attribute you expected is not there, the problem is in the parent's markup.
- Read the console. Read-only violations and bad decorator use produce messages that name the property.
- Use the
debuggerstatement in a setter and step through the call stack to see which parent expression supplied the value. - Reduce the problem. Replace the dynamic binding with a literal string. If the literal works, the child is fine and the parent's data is wrong.
The table maps common symptoms to likely causes.
| Symptom | Likely cause |
|---|---|
| The child shows `undefined` | Missing `@api`, camelCase attribute, or the value is read before it arrives |
| The child shows the variable name as text | Quotes used instead of braces |
| A boolean cannot be turned off | The property defaults to `true`, or `"false"` was written as text |
| Console error about a read-only value | The child assigned to a received value or mutated a received object |
| The setter runs but the screen stays the same | The setter does not store the value, or stores it in a field the template does not read |
| `TypeError` when calling a child method | `querySelector` returned `null` |
| Wrong rows change after sorting | Loop keys are indexes, not stable ids |
Exercise
A child component has @api isActive = true;. The parent writes <c-badge is-active="false"></c-badge> and the badge still shows as active. Give two reasons this happens and the fix for each.
Show answer
First, the attribute is present, so the child receives the string "false", which is truthy. Second, the default is true, so omitting the attribute cannot turn the flag off. Fix both by changing the child to @api isActive = false; and having the parent either leave the attribute out or bind a real boolean, for example is-active={badgeIsActive}.
Exercise
A child receives @api tasks and runs this.tasks.sort(...) in a click handler. The console reports an error. Explain why, and write the corrected approach.
Show answer
sort changes the array in place, and the array belongs to the parent, so the framework blocks the change. Copy the array in a setter and sort the copy, or sort a copy in the handler: this._tasks = [...this._tasks].sort((a, b) => a.name.localeCompare(b.name));. The child's tasks getter should return this._tasks.
Exercise
A parent template contains <c-task-card key={index} heading={task.name}></c-task-card> inside for:each. After the user deletes the first task, the remaining cards show the wrong state. What is wrong?
Show answer
The key is the array index, which changes for every item after a deletion, so the framework matches cards to the wrong items. Use a unique, stable id from the data, such as key={task.id}.