I am trying to understand Redux online tutorials that are posted by Dan Abramov. At present I am on the following sample:
Reducer composition with Arrays
Here is my practice code following the above sample:
// Individual TODO Reducer
const todoReducer = (state, action) => {
switch(action.type) {
case 'ADD_TODO':
return {
id: action.id,
text: action.text,
completed: false
};
case 'TOGGLE_TODO':
if (state.id != action.id) return state;
// This not working
/*
return {
...state,
completed: !state.completed
};
*/
//This works
var newState = {id: state.id, text: state.text, completed: !state.completed};
return newState;
default:
return state;
}
};
//TODOS Reducer
const todos = (state = [], action) => {
switch(action.type) {
case 'ADD_TODO':
return [
...state,
todoReducer(null, action)
];
case 'TOGGLE_TODO':
return state.map(t => todoReducer(t, action));
default:
return state;
}
};
//Test 1
const testAddTodo = () => {
const stateBefore = [];
const action = {
type: 'ADD_TODO',
id: 0,
text: 'Learn Redux'
};
const stateAfter = [{
id: 0,
text: "Learn Redux",
completed: false
}];
//Freeze
deepFreeze(stateBefore);
deepFreeze(action);
// Test
expect(
todos(stateBefore, action)
).toEqual(stateAfter);
};
//Test 2
const testToggleTodo = () => {
const stateBefore = [{id: 0,
text: "Learn Redux",
completed: false
}, {
id: 1,
text: "Go Shopping",
completed: false
}];
const action = {
type: 'TOGGLE_TODO',
id: 1
};
const stateAfter = [{
id: 0,
text: "Learn Redux",
completed: false
}, {
id: 1,
text: "Go Shopping",
completed: true
}];
//Freeze
deepFreeze(stateBefore);
deepFreeze(action);
// Expect
expect(
todos(stateBefore, action)
).toEqual(stateAfter);
};
testAddTodo();
testToggleTodo();
console.log("All tests passed");
Issue is, within the todoReducer function, following syntax is not working:
return {
...state,
completed: !state.completed
};
I am using Firefox version 44.0 and it shows me following error in console:
Invalid property id
Now I guess my current version of Firefox must support Spread operator. If anyway it does not, is there any way to add some standalone Polyfill to support this syntax?
Here is also the JSFiddle
The object spread syntax is not supported in most browsers at the minute. It's proposed for addition in ES7 (aka ES2016). As far as I know there's no way to polyfill it, as it uses a new syntax rather than just being a function call.
You have two options in the meantime.
1) Use Object.assign
to create an updated version of the object, like so:
Object.assign({}, state, {
completed: !state.completed
});
Although this will also need to be polyfilled in most browsers - a good example one is available on MDN, or you can use a third party library's version, like the one in lodash.
2) Use transpiling tools like Babel, which allow you to write your code with newer syntax and then convert it to a version that works in all browsers.