The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

Refactoring mutations to enforce immutable data in Angular 2

Refactoring mutations to enforce immutable data in Angular 2

4:16
When a Todo property updates, you still must create a new Array of Todos and assign a new reference. This lesson walks you through refactoring from the current approach to the immutable approach.
Watch this lesson now
Avatar
egghead.io

When a Todo property updates, you still must create a new Array of Todos and assign a new reference. This lesson walks you through refactoring from the current approach to the immutable approach.

Avatar
Nik

Nice videos! -- I just have a question about the toggle todo immutability approach. When before you reconstruct the todos array with slice(0,1) and etc, the todo in question whose status is set to completed by todo.toggle(), would't this mean that we are changing its state, an act that we try to avoid?

In reply to egghead.io
Avatar
John

Good catch ;) That's addressed in a later lesson, so keep watching! (and check out our other lessons on immutable libraries which are out of scope of this series).

In reply to Nik
Avatar
Mario

WHen it toggles, why not doing this.todos = [...this.todos] instead of looking for the index to mount again the same exact array in three parts?

In reply to egghead.io
Avatar
oalexandersson

WHen it toggles, why not doing this.todos = [...this.todos] instead of looking for the index to mount again the same exact array in three parts?

I want to know this as well.

In reply to Mario
Avatar
John

This is in preparation for a later lesson when we talk more about immutability. You wouldn't be using the "exact same array", you're making a brand new array composed of the three parts including copying the todo with the changed toggled prop (as opposed to updating a todo's prop).

In reply to Mario
Avatar
Andre

this.todos = [
...this.todos.slice(0, i),
todo,
...this.todos.slice(i + 1)
];

I don't understand how the todo item being toggled is being removed when it's being added back to the array in the todoToggle function?

Avatar
Andre

Answered my own question by looking back at previous code. I had forgotten about the 'started pipe' that was created in an earlier lesson, which is filtering the list of todo items that are then outputted by the *ngFor.

In reply to Andre
HEY, QUICK QUESTION!
Joel's Head
Why are we asking?