Never Mutate State dispatch issue

Never Mutate State dispatch issue
0.0 0

#1

Tell us what’s happening:
Hi I am getting following error :slight_smile:
The Redux store should exist and initialize with a state equal to the todos array in the code editor.
Dispatching an action of type ADD_TO_DO on the Redux store should add a todo item and should NOT mutate state.

I tried to solve the by looking into the forum but getting error .

Please help

Your code so far


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 arr = state.map(x => x);
      arr.push(action.todo);
      return arr;
      break;

      // don't mutate state here or the tests will fail
    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);
store.dispatch(addToDo("Learn React!"));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/redux/never-mutate-state


Redux: Never Mutate State Slice vs. Concat
#2

Sorry …I just solved the problem by removing the following line from code:

store.dispatch(addToDo(“Learn React!”));


#3

But
Could anyone help me in understanding why I am able to pass this test while I am not passing 'Learn react ’ argument anywhere in the code .

Sorry for asking such dumb question …I am new to Redux .


#4

“Learn React” is just an example they give you and the exercise doesn’t actually expect you to pass in that string.

Since, you already wrote how to handle incoming actions with todo item, you are able to pass the test. :sunglasses:


#5

Using spread operator worked for me

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