How do you return a new copy of state in Redux?

How do you return a new copy of state in Redux?
0.0 0

#1

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

Right now I’m defining the state as a new variable, but the tests still say that I am mutating the state. What am I doing wrong in this challenge? Any help is appreciated :slight_smile:

My 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 newState =  state.push(action.todo);
      return newState;
      break;
    default:
      return state;
  }
};

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

const store = Redux.createStore(immutableReducer);

Browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.


#2

push alters the array in which is it called on, so the above line mutates state. Think about another array method which can be used to add an element onto the end of an existing array, but returns a new array instead.