1. 10
    Redux: Avoiding Object Mutations with Object.assign() and ...spread
    2m 38s

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

Dan Abramov
InstructorDan Abramov

Share this video with your friends

Send Tweet
Published 7 years ago
Updated a year ago

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

[00:00] Like in previous example, I use expect and deep freeze libraries from NPM to make my test assertions. This time, I'm testing a function called toggle to-do that takes our to-do object and flips its completed field. If completed was false, it should be true in the return value. If it was true, it should be false.

[00:22] Just like in the previous lesson, I'm going to start by writing a mutated version that passes the current test. A mutated version just flips the completed field, reassigns it on the past object.

[00:35] While it works, we know that mutations are not allowed in Redux. So to enforce this, I'm calling deep freeze on my to-do object. I'm not allowed to change its completed field anymore.

[00:46] One way out of this would be to create the new object with every field copied from the original object except the completed field, which would be flipped. However, if we later add new properties to the new object, we might forget to update this piece of code to include them.

[01:04] This is why I suggest you to use object assign method, which is new to ES6. It lets you assign properties of several objects onto the target object.Note how the object assign argument order corresponds to that of the JavaScript assignment operator.

[01:24] The left argument is the one whose properties are going to be assigned, so it's going to be mutated. This is why we're passing an empty object as the first argument, so we don't mutate any existing data. Every further argument to object assign will be considered one of the source objects whose properties will be copied to the target object.

[01:46] It is important that if several sources specify different values for the same property, the last one wins. This is what we use to override the completed field despite what the original to-do object says.

[02:01] Finally, you need to remember that object assign is a new method in ES6, so it is not natively available in all the browsers. You should use a polyfill, either the one that ships with Babel or a standalone object assign polyfill, to use it without risking crashing your website.

[02:21] Another option that doesn't require a polyfill is to use the new object spread operator, which is not part of ES6. However, it is proposed for ES7. It is fairly popular, and it is enabled in Babel if you use the stage two preset.

Lars Rye Jeppesen
Lars Rye Jeppesen
~ 7 years ago

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

Simon Vrachliotis
Simon Vrachliotis
~ 7 years ago

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

Dan Abramov
Dan Abramovinstructor
~ 7 years ago

I’m glad to have tricked you!

Liang
Liang
~ 7 years ago

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

Dan Abramov
Dan Abramovinstructor
~ 7 years ago

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.

jean-michel
jean-michel
~ 6 years ago

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}); };

~ 6 years ago

It seems the spread operator in object deconstruction is not supported by ES6.

http://stackoverflow.com/questions/31115276/ecmascript-6-spread-operator-in-object-deconstruction-support-in-typescript-and

Jiwon
Jiwon
~ 5 years ago

This course is very helpful to understand redux and es6. Thank you for Dan!! Good job!

Christian
Christian
~ 4 years ago

Avoiding object mutations is made way easier with Immutable JS:

const { Map } = Immutable;

const toggleTodo = todo => {
  return todo.update("completed", completed => !completed);
};

const testToggleTodo = () => {
  const todoBefore = Map({
    id: 0,
    text: "Learn Redux",
    completed: false
  });
  const todoAfter = Map({
    id: 0,
    text: "Learn Redux",
    completed: true
  });

  expect(toggleTodo(todoBefore)).toEqual(todoAfter);
  expect(todoBefore.get("completed")).toEqual(false);
};

testToggleTodo();
console.log("All tests passed.");
Charles Owen
Charles Owen
~ 4 years ago

This may be merely a question of semantics, but according to the documentation on MDN, Object.assign does not merely copy properties from source to target, rather it calls getters on the source and setters on the target.

"The Object.assign() method only copies enumerable and own properties from a source object to a target object. It uses [[Get]] on the source and [[Set]] on the target, so it will invoke getters and setters. Therefore it assigns properties versus just copying or defining new properties."

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign