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

Redux: Avoiding Object Mutations with Object.assign() and ...spread

Redux: Avoiding Object Mutations with Object.assign() and ...spread

2:38
Learn how to use Object.assign() and the spread operator proposed for ES7 to avoid mutating objects.
Watch this lesson now
Avatar
egghead.io

Learn how to use Object.assign() and the spread operator proposed for ES7 to avoid mutating objects.

Avatar
Lars Rye Jeppesen

This is really cool stuff.. gonna use this with Angular2. Thank you

Avatar
Simon

Came to learn about Redux, finding myself learning a lot about pure functions and immutability... This is awesome!

Avatar
Dan Abramov

I’m glad to have tricked you!

In reply to Simon
Avatar
Liang

"...todo" is like shallow copy? Would that be problematic if each todo obj is actually a more complicated and nested obj?

Avatar
Dan Abramov

Yes, it will make a shallow copy. If you change a single field on it, it would not be a problem because you want to keep all other properties the same even if they are nested objects. Shallow copy is exactly what you need when you change a specific single field.

However if you want to perform a deep change it will be more complicated: you will need to shallowly copy all objects “on the way to” that change. This is exactly where you’d use the reducer composition pattern again, to delegate updating some field to a subreducer.

In reply to Liang
Avatar
jean-michel

while Object.assign() would do the job, curious to know why you have not mention the usage of lodash

The following would do the job with the pure function constraint respected

function toggleTodo(todo) {
return .assign(.clone(todo), {completed: !todo.completed});
};

Avatar
Brutalis

somehow I can't use the wzrd source in the script tags anymore, I only get expect is not defined AND when I try to go to https://wzrd.in, google chrome blocks it (privacy error). Also for the link: https://wzrd.in/standalone/expect@latest. Which can I use to make this work again for me (using jsbin)

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