Redux: Never Mutate State Slice vs. Concat

I am having trouble understanding why my code doesn’t work. When I run the following, I receive the error “Dispatching an action of type ADD_TO_DO on the Redux store should add a todo item and should NOT mutate state.”

const ADD_TO_DO = 'ADD_TO_DO';

// A list of strings representing tasks to do:
const todos = [
  'Go to the store',
  'Clean the house',
  'Cook dinner',
  'Learn to code',
];

const immutableReducer = (state = todos, action) => {
  switch(action.type) {
    case ADD_TO_DO:
      // don't mutate state here or the tests will fail
      return state.slice().push(action.todo);  // THIS LINE
    default:
      return state;
  }
};

// an example todo argument would be 'Learn React',
const addToDo = (todo) => {
  return {
    type: ADD_TO_DO,
    todo: todo
  }
}

const store = Redux.createStore(immutableReducer);

However, I am able to pass the test by changing the line to return state.concat(action.todo);

Neither concat nor slice changes the original array, so why am I failing the test with my original solution?

You can take a look at this thread that I replied before.

Thank you, but that doesn’t answer my question. I am able to solve the task, but I am confused as to why concat works and slice does not

Ok, I missed your question at the bottom. slice and concat should both work. Since the exercise just came off of beta version, it looks like there is still a bug.

1 Like

I see, thank you for your help!

1 Like

But in this case, it’s not a bug. The push() method adds one or more elements to the end of an array and returns the new length of the array.

From MDN web docs:

“The push() method adds one or more elements to the end of an array and returns the new length of the array.”

Source: Array.prototype.push() - JavaScript | MDN

You can use the slice() method to clone “state” and then push the “todo” element to the new array. To return an updated new array, you could do this:

var newState = state.slice();
      newState.push(action.todo);
      return newState;

This passed the tests.
There are cleaner ways of passing the tests, however.