Sub topic 13
Common mistakes and how to fix them
This chapter assumes you can write an LWC template and class, bind properties with curly braces, use lwc:if, and call map on an array. It covers the list mistakes that cause the most trouble and how to find each one.
The three key mistakes
The key attribute lets the engine match each rendered element to its array item when the list changes. Most list bugs come from keys.
| Mistake | Symptom | Fix |
|---|---|---|
| Missing key | Compile error, or the component fails to deploy | Put `key={item.Id}` on the first element inside the iteration |
| Duplicate key | Wrong rows update, or rows show stale content | Use a field that is unique within the list |
| Index as key | Input values and focus jump to the wrong row after a reorder or removal | Use a stable identifier from the data |
Putting the key on the wrong element
The key goes on the first element inside the <template for:each> tag. It does not go on the <template> tag itself, and it does not go on a nested child.
<!-- Wrong: the key is on a child, not the first element -->
<template for:each={contacts} for:item="contact">
<li key={contact.Id}>
<span>{contact.Name}</span>
</li>
</template>The block above is correct, because li is the first element. If you wrap the li in a div, move the key to the div.
Using the index as the key
The index changes whenever items are added, removed or reordered. The engine then reuses the wrong element for the wrong item. The list looks right at first, so this bug often appears late.
<!-- Wrong: position is not a stable identifier -->
<template for:each={contacts} for:item="contact" for:index="position">
<li key={position}>{contact.Name}</li>
</template>Use key={contact.Id} instead. If your data has no identifier, add one when you build the array, for example with a counter or a generated value.
Expressions in the template
Templates cannot run JavaScript. These all fail:
<li class={contact.Id === selectedId ? 'selected' : ''}>{contact.Name.toUpperCase()}</li>Compute the value in JavaScript and bind the result. This getter adds a cssClass and an uppercase name to each item.
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
selectedId;
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' }
];
get decoratedContacts() {
return this.contacts.map((contact) => ({
...contact,
cssClass: contact.Id === this.selectedId ? 'selected' : '',
upperName: contact.Name.toUpperCase()
}));
}
}Then bind class={contact.cssClass} and {contact.upperName} over decoratedContacts.
Updates that do not render
If you change a list and the page stays the same, check how you changed it.
// Risky: mutates the existing array in place
this.contacts.push({ Id: '003C', Name: 'New Contact' });
// Safe: assigns a new array
this.contacts = [...this.contacts, { Id: '003C', Name: 'New Contact' }];Class fields are reactive, and deep changes to plain objects and arrays are tracked in current LWC. This does not apply to objects that come from outside, such as wire results, which are read-only. Assigning a new array works in every case and makes the intent clear. When you copy a wire result, build a new array with map or spread instead of editing the original.
Other common errors
- Reading
datasetfrom the wrong element. In a handler, useevent.currentTarget.dataset.id.event.targetcan be a child of the clicked element, and itsdatasetis empty. - Writing
data-idin camel case. HTML attributes are lowercase.data-contact-idbecomesdataset.contactId. - Forgetting the empty state. An empty array renders an empty
ul. Guard it withlwc:if={hasContacts}and anlwc:elsemessage. - Using
it.valueas the item name infor:each.value,firstandlastexist only withiterator. Withfor:each, use the name fromfor:item.
A debugging routine
- Open the browser console and look for key warnings or compile errors.
- Log the array in the class and confirm that every item has the field you use as the key.
- Check that the keys are unique, as in the snippet below.
- Confirm that you assigned a new array when the data changed.
const ids = this.contacts.map((contact) => contact.Id);
const hasDuplicates = new Set(ids).size !== ids.length;
console.log('IDs:', ids, 'Duplicates:', hasDuplicates);Exercise
A list of rows has text inputs. After you delete the first row, the remaining rows show each other's typed text. The template uses key={position} from for:index. What is the cause, and what is the fix?
Show answer
The index changes when a row is removed, so the engine reuses the element at each position for a different item, and the typed text stays with the element. Use a stable identifier from the data, such as key={contact.Id}.
Exercise
A click handler calls event.target.dataset.id and returns undefined when you click the contact's name inside a span. How do you fix it?
Show answer
Use event.currentTarget.dataset.id. currentTarget is the li that has the data-id attribute, while target is the span that was clicked.