Using Array ...spread to enforce Pipe immutability.

John Lindquist
InstructorJohn Lindquist

Share this video with your friends

Send Tweet
Published 6 years ago
Updated 3 years ago

Pipes need a new reference or else they will not update their output. In this lesson you will use the Array ...spread operator to create new Array to update pipe output without mutation.

[00:00] Now without knowing it, we've kind of coded ourself into a corner, because if I try to add more items -- shave, or swim, or anything like that -- you can see I keep getting my TODO models. They're added, but they're not showing up in my list.

[00:18] That's because a pipe expects a new reference to come into its transform method, or else it's not going to run at all. It's not going to check to see if any of the values inside of the array changed or if any items are added or removed to the array through something like push.

[00:33] This is where immutability comes in, because instead of doing todos.push, which is essentially saying use this same array and add a new TODO model onto it, we're going to create a new method on our service called "add TODO" then jump into our TODO service. Say, "Add TODO," which takes in a TODO, which is a TODO model.

[00:57] This time, instead of saying todos.push, we're going to say that TODOs is a new array, because we need our TODOs to point to something completely different. We'll use the spread operator, so this.todos, to essentially say, "Copy over the old TODOs and put them in this new array, and then add the new TODO to the end of that array."

[01:17] When I save now I can add another TODO model like shave, swim, saunter, sally forth. Each time I add a new TODO model, because this reference is changing, it's not pointing to the same array, the search pipe filter knows to kick in and run the value.filter whenever that reference changes.

[01:38] Now if you think this is more work, or it's incredibly difficult, or it's different, the main reason is because it gives you a huge performance boost by saving Angular from checking every single time an individual property or value changes on something that gets passed into a...

kevin
kevin
~ 6 years ago

Ugg this is more work and its incredibly difficult and it is different.

John Lindquist
John Lindquistinstructor
~ 6 years ago

There are libraries that make this much easier, but they aren't built into Angular 2 by default so I showed the "vanilla JavaScript way".