Sub topic 11
Updating a List So the Template Re-renders
This chapter assumes you can write a basic LWC with for:each, you know why each item needs a stable key, and you are comfortable with array methods such as map and filter. Here you will learn how to change list data so the template updates, and which kinds of change it notices.
How LWC decides to re-render
An LWC component re-renders when a value that the template reads has changed. Class fields are reactive. Reassigning a field counts as a change. Since the Spring '20 release, LWC also tracks changes inside plain objects and arrays that you assign to a field. Even so, the most predictable pattern is to build a new array and assign it to the field.
Replacing the array has three advantages:
- The change is easy to see in code, because there is one assignment.
- It works the same for arrays that come from
@wireor Apex, which can be read-only. - It avoids bugs from methods that change an array without a visible assignment.
Add, remove and change items
Each operation below returns a new array and assigns it to this.contacts.
import { LightningElement } from 'lwc';
export default class ContactList extends LightningElement {
contacts = [
{ Id: '003A', Name: 'Amy Taylor' },
{ Id: '003B', Name: 'Ravi Patel' }
];
addContact() {
const id = '003' + Date.now();
this.contacts = [...this.contacts, { Id: id, Name: 'New Contact' }];
}
removeContact(event) {
const id = event.currentTarget.dataset.id;
this.contacts = this.contacts.filter((contact) => contact.Id !== id);
}
renameContact(event) {
const id = event.currentTarget.dataset.id;
this.contacts = this.contacts.map((contact) =>
contact.Id === id ? { ...contact, Name: 'Renamed' } : contact
);
}
}- Add: use the spread operator,
[...this.contacts, newItem]. - Remove: use
filterto keep every item except the one you want gone. - Change: use
map, and return a copy of the matching item with{ ...contact, Name: 'Renamed' }.
Each new item gets a new Id, so it has its own key. Items you did not touch keep their keys. This lets LWC reuse the existing DOM elements for them and only create, remove or update the elements that changed.
Mutating in place
Methods such as push, splice and sort change the existing array. Code like this may or may not update the screen, depending on where the array came from:
// Risky: changes the array without assigning a new one
this.contacts.push({ Id: '003Z', Name: 'Zed' });If the array was set directly in your class, recent LWC versions usually notice the change. If it came from @wire or from Apex, it is frozen, and push throws an error. Copying first avoids both cases:
const sorted = [...this.contacts].sort((a, b) => a.Name.localeCompare(b.Name));
this.contacts = sorted;Note that sort runs on a copy here, so the original array is untouched.
Keys during updates
Keys matter most when the list changes. If you use the index as the key, removing the first item shifts every later item to a new key. LWC then updates many elements instead of one, and any state held in those elements, such as a typed value in an input, can end up on the wrong row. Use a stable identifier from the data, such as a record Id.
Updating a field read by a getter
The decoratedContacts getter from earlier chapters reads this.contacts and this.selectedId. It runs again whenever either field changes. You do not need to call it yourself. Changing selectedId in the click handler is enough to refresh the cssClass values.
Exercise
A handler calls this.contacts.splice(0, 1) on an array returned by an Apex wire adapter, and the component throws an error. What is the likely cause, and what is the fix?
Show answer
Data from @wire is read-only, so in-place methods such as splice fail. Build a new array instead, for example this.contacts = this.contacts.slice(1) or a filter call, and assign it to the field.
Exercise
Why is key={position} (the for:index value) a poor choice in a list where users can delete rows?
Show answer
After a deletion, every later item gets a new index, so its key changes. LWC treats those items as different, updates more elements than needed, and can attach element state to the wrong row. A stable Id from the data avoids this.