Redux: Remove item from array

Redux: Remove item from array
0

#1

What I’m doing wrong here?

const immutableReducer = (state = [0,1,2,3,4,5], action) => {
  switch(action.type) {
    case 'REMOVE_ITEM':
      // don't mutate state here or the tests will fail
      let newArr = [...state.slice(0,action.index)];
      return newArr;
    default:
      return state;
  }
};

const removeItem = (index) => {
  return {
    type: 'REMOVE_ITEM',
    index
  }
}

const store = Redux.createStore(immutableReducer);

https://learn.freecodecamp.org/front-end-libraries/redux/remove-an-item-from-an-array

Error in console:

// running test
Dispatching the removeItem action creator should remove items from the state and should NOT mutate state.
// tests completed


#2

It would be correct to say that state isn’t being mutated. However, the way you are removing the item from the array needs a revision.

Right now, if you used the slice() method with action.index being your end index and 0 as your starting index, it would return back with that portion of the array

 let newArr = state.slice(0, 3) //[ 1, 2, 3 ]

We’re not creating a new array from a portion of the state array. We’re simply deleting that index in the state array.

So, we should use the .filter() array method, and only returning all the indices that don’t equal our index we want to remove

const immutableReducer = (state = [0,1,2,3,4,5], action) => {
  switch(action.type) {
    case 'REMOVE_ITEM':
      let newArr = [...state.filter((elem, idx) => { // [1,2,3,5]
        return idx !== action.index
      })];
      return newArr;
    default:
      return state;
  }
};

const removeItem = (index) => {
  return {
    type: 'REMOVE_ITEM',
    index
  }
}

const store = Redux.createStore(immutableReducer);