Redux: Never Mutate State Slice vs. Concat

Redux: Never Mutate State Slice vs. Concat
0.0 0

#1

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?


#2

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


#3

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


#4

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.


#5

I see, thank you for your help!