Learn how to use Object.assign() and the spread operator proposed for ES7 to avoid mutating objects.
This is really cool stuff.. gonna use this with Angular2. Thank you
Came to learn about Redux, finding myself learning a lot about pure functions and immutability... This is awesome!
I’m glad to have tricked you!
"...todo" is like shallow copy? Would that be problematic if each todo obj is actually a more complicated and nested obj?
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.
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}); };
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
This course is very helpful to understand redux and es6. Thank you for Dan!! Good job!
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.");
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