Shallow array copies
Let's use a shallow copy of our array to track changes.
Summary
The @tracked
decorator works by tracking reference changes. For example, if we reassign a tracked property from the string "hello"
to "world"
, then Ember knows to re-render any templates using that property.
However, when we push items into a native JavaScript array we are not reassigning the array, instead we're mutating the array. Ember is unable to track the array change since no reassignment took place.
Creating a shallow copy of the array, and then reassigning our tracked property to that new array is a great way to let Ember know a change happened. This technique is commonly used in other JavaScript frameworks.
@action addListItem() {
// create a shallow copy of this.items
let itemsCopy = [...this.items];
itemsCopy.push(randomCatUrl());
// reassign this.items
this.items = itemsCopy;
}