Sub topic 13
Common mistakes and how to fix them
This chapter assumes you can already render a list with for:each and iterator, and that you know how a component's template and class connect. It collects the errors that come up most often when you build list templates. For each one it gives the symptom, the cause, and the fix.
A debugging order that saves time
Most list problems fall into three groups: the template does not compile, the list renders wrongly, or the list does not update. Work through them in that order.
Mistake 1: a missing key
The compiler requires a key on the first element inside every iteration. Without it the template does not compile.
<!-- Broken: no key -->
<template>
<ul>
<template for:each={contacts} for:item="contact">
<li>{contact.Name}</li>
</template>
</ul>
</template>Add key={contact.Id} to the li. The key lets the engine match each existing DOM node to its data item when the array changes. Without that match it cannot safely reuse or move nodes.
Mistake 2: the key is on the wrong element
The key belongs on the first element that is a direct child of the iteration <template>. It does not go on the <template> tag, and it does not go on an element nested deeper.
<!-- Broken: key is on a child, not on the wrapper -->
<template for:each={contacts} for:item="contact">
<div class="row">
<span key={contact.Id}>{contact.Name}</span>
</div>
</template><!-- Fixed: key is on the first element in the iteration -->
<template for:each={contacts} for:item="contact">
<div key={contact.Id} class="row">
<span>{contact.Name}</span>
</div>
</template>Mistake 3: duplicate keys
Keys must be unique among siblings in the same list. If two items share a key, the template compiles, but the engine treats them as one identity. You may see stale text, an item that is missing, or an item that appears twice after an update.
Duplicates usually come from one of these causes:
- Using a field that is not unique, such as
contact.AccountIdorcontact.Name. - Building test data by copying one object several times.
- Merging two arrays that each contain the same record.
To find a duplicate, log the keys and compare the array length with the number of distinct values.
const ids = this.contacts.map((contact) => contact.Id);
const unique = new Set(ids);
console.log('items:', ids.length, 'unique keys:', unique.size);If the two numbers differ, you have a duplicate. Fix the data, or choose a field that is unique. A record Id is the best choice because it does not change when the list is reordered or filtered.
Mistake 4: using the index as the key
The index is tempting because every item has one. It is a poor key because the index describes a position, not an item. If you remove the first item, every later item gets a new index, so the engine believes they all changed.
The LWC compiler rejects a key bound directly to the for:index value, so you will usually see this as a compile error. The same reasoning applies to keys you build from the position, such as contact.Name + position.
<!-- Broken: key is derived from the index -->
<template for:each={contacts} for:item="contact" for:index="position">
<li key={position}>{contact.Name}</li>
</template>Use for:index for display or for a data attribute, as in data-position={position}. Keep key on a stable identifier. If your data has no Id, add one when you create the items, for example with a counter that never repeats.
Mistake 5: expressions in the template
Templates bind to properties and simple property paths. They do not evaluate JavaScript expressions. These all fail to compile or do not do what you expect:
<!-- Broken: expressions are not allowed in braces -->
<li key={contact.Id} class={contact.Id === selectedId ? 'selected' : ''}>
{contact.Name.toUpperCase()}
</li>
<p lwc:if={contacts.length > 0}>Contacts found</p>Move the logic into JavaScript, and bind the template to the result. Two patterns cover nearly every case:
- For one value of the whole component, write a getter, such as
get hasContacts(). - For one value per item, build a decorated array with
map, as indecoratedContacts.
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
selectedId;
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' }
];
get hasContacts() {
return this.contacts.length > 0;
}
get decoratedContacts() {
return this.contacts.map((contact) => ({
...contact,
displayName: contact.Name.toUpperCase(),
cssClass: contact.Id === this.selectedId ? 'selected' : ''
}));
}
}<template>
<ul lwc:if={hasContacts}>
<template for:each={decoratedContacts} for:item="contact">
<li key={contact.Id} class={contact.cssClass}>{contact.displayName}</li>
</template>
</ul>
</template>Note that the template iterates decoratedContacts, not contacts. A common slip is to compute the decorated array and then keep iterating the original one, so the new fields show up as blank.
Mistake 6: forgetting `.value` with `iterator`
With for:each, the loop variable is the item. With iterator:it, the loop variable is a wrapper object, and the item is it.value.
| You wrote | What happens | Fix |
|---|---|---|
| `key={it.Id}` | The wrapper has no `Id`, so the key is undefined | `key={it.value.Id}` |
| `{it.Name}` | Blank output | `{it.value.Name}` |
| `lwc:if={it.isFirst}` | Never true | `lwc:if={it.first}` |
| `{contact.Name}` inside `iterator:it` | The name `contact` is not defined | `{it.value.Name}` |
The wrapper properties are value, index, first, and last. The names are fixed, and only the variable name after iterator: is yours to choose.
Mistake 7: the list does not update
Suppose a button handler runs, the data is correct in the debugger, and the screen does not change. The usual cause is that the component never saw a reassignment.
// Broken: changes the array but the field still points to the same array
addContact() {
this.contacts.push({ Id: '003C', Name: 'New Contact' });
}// Fixed: assign a new array
addContact() {
this.contacts = [
...this.contacts,
{ Id: '003C', Name: 'New Contact' }
];
}Assigning a new array is the pattern to use by default. It also works the same way for removal and edits:
removeContact(id) {
this.contacts = this.contacts.filter((contact) => contact.Id !== id);
}
renameContact(id, name) {
this.contacts = this.contacts.map((contact) =>
contact.Id === id ? { ...contact, Name: name } : contact
);
}A related error appears with data you did not create. Arrays that arrive through an @api property, or from a wire service, are read-only. Calling push, sort, or assigning to a property of an item throws an error. Copy first, then change the copy, for example with [...this.items].sort(...) or { ...item, selected: true }.
Mistake 8: reading the wrong element in a click handler
A click handler on an li can receive events from anything inside the li, such as a nested span. The event.target property is the element that was actually clicked, so it may be the span, and a span has no data-id.
// Broken: target may be a child of the li
handleSelect(event) {
this.selectedId = event.target.dataset.id;
}
// Fixed: currentTarget is the element that has the handler
handleSelect(event) {
this.selectedId = event.currentTarget.dataset.id;
}Two more details about data attributes cause trouble:
- The name converts from kebab case to camel case.
data-contact-idbecomesdataset.contactId. - Every value is a string.
data-position={position}gives you"2", not2. Convert it withNumber(...)before you use it as an array index, and compare Ids as strings.
Mistake 9: nested lists with shared names or missing inner keys
Each loop needs its own key. In a nested list, the outer items need a key and the inner items need a key. Use different for:item names so the inner loop does not hide the outer one.
<template>
<template for:each={accounts} for:item="account">
<section key={account.Id}>
<h3>{account.Name}</h3>
<ul>
<template for:each={account.contacts} for:item="contact">
<li key={contact.Id}>{contact.Name}</li>
</template>
</ul>
</section>
</template>
</template>Inner keys only need to be unique within their own list. Two accounts can each contain a contact with the same Id in principle, but real record Ids are unique anyway.
Mistake 10: syntax slips in the directive
A few errors are about typing rather than design:
- Quoting the array: write
for:each={contacts}, with braces and no quotation marks. - Putting braces on
for:item: it takes a plain string, so writefor:item="contact". - Using the item name outside the loop:
contactexists only inside the iteration template. - Putting
for:eachanditeratoron the same tag.
Quick reference
| Symptom | Likely cause | First fix to try |
|---|---|---|
| Compile error about a key | Key missing, or on the wrong element | Put `key` on the first element inside the iteration |
| Compile error about key value | Key bound to the index | Bind to a stable Id |
| Items repeat or go stale | Duplicate keys | Log keys and compare with `Set` |
| Blank text for each item | Used `it.Name` instead of `it.value.Name` | Read through `value` |
| Computed field is blank | Iterating the original array | Iterate the decorated array |
| List ignores `push` | Array changed in place | Assign a new array |
| Handler reads `undefined` | `event.target` is a child | Use `event.currentTarget` |
Exercise
A component keeps its items in this.items. A button handler calls this.items.push(newItem). The data is correct in the debugger, but the list on screen does not change. What is wrong, and how do you fix it?
Show answer
The handler changes the existing array without reassigning the field, so the component does not re-render. Replace the push with an assignment of a new array, such as this.items = [...this.items, newItem];.
Exercise
An li inside for:each has onclick={handleSelect} and contains a <span> with the contact name. The handler uses event.target.dataset.id and sometimes returns undefined. Why does this happen, and what should the handler read instead?
Show answer
When the user clicks the span, event.target is the span, which has no data-id. event.currentTarget is the li that owns the handler, so the handler should read event.currentTarget.dataset.id.
Exercise
Your template uses iterator:it={contacts} and renders <li key={it.Id}>{it.Name}</li>. List two things wrong with it and give the corrected line.
Show answer
The item is wrapped, so Id and Name must be read through value. The key is undefined and the text is blank. The corrected line is <li key={it.value.Id}>{it.value.Name}</li>.