how to remove last element in the redux store array?

Viewed 2066

I have following code:

const initialState = {
  searchItems: ['Item'],
}
export default (state = initialState, action) => {
  switch (action.type) {
    case BACKSPACE_REMOVE_SEARCH_ITEM:
      console.log(state.searchItems);
      return {
        ...state,
        searchItems: [...state.searchItems.splice(-1)],
      };
    default:
      return state;
  }
}

but when I try to execute such an action I receive same array as before with 'Item' inside, it doesn't' remove it. Where is a problem?

1 Answers

.splice returns the deleted elements. Actually, you shouldn't use .splice at all since it mutates the original array. I know you are spreading the original one but spread syntax makes shallow copies. So, be careful. .slice would be better it also returns the deleted ones. In this case, you need to use a combination of .slice and .concat probably or you can use .filter.

return {
    ...state,
    searchItems: state.searchItems.filter( (_,i) => 
        i !== state.searchItems.length-1
    ),
};
Related