Redux: Never Mutate State - Slice/Splice

Hi, this code doesn’t pass the test and I dont know why! The error is “Dispatching an action of type ADD_TO_DO on the Redux store should add a todo item and should NOT mutate state” But I dont get it, cause my code meets the requirement. Pls, help me

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:
        let newArr = state.slice();
        newArr.splice(newArr.length, 0, action.todo);
        console.log(newArr);
        return newArr;
    default:
      return state;
  }
};

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

const store = Redux.createStore(immutableReducer);

You are passing in “Learn React”. The comment above just meant that as example. You will need to pass in ‘todo’.

shim is correct, but just to be clear, you’re not passing a string, you’re passing the variable called todo, that you passed in here:

const addToDo = (todo) => {

That is what you want to use in your action creator.

Also, due to es6 destructuring, you don’t even need to assign the todo variable to the todo key, as they are the same. You can just leave the object as:


const addToDo = (todo) => {
  return {
    type: ADD_TO_DO,
    todo
  }
}

Behind the scenes the code will transpile to:


const addToDo = (todo) => {
  return {
    type: ADD_TO_DO,
    todo: todo
  }
}

OMG! Yes, you’re right! Thanks.

We usually try to avoid giving the answer but prefer to lead them in the right direction. And remember that if you do post an answer, to wrap it in [spoiler] tags. Also, instead of <code><pre> you can just use three backticks on the line before and three backticks on the line after.

Thanks for the tips. However, the code I provided is given in the challenge by default. I was merely explaining why this part of the code doesn’t need to be touched. https://learn.freecodecamp.org/front-end-libraries/redux/never-mutate-state

You’re right, I apologize. :blush: