Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to remove last element in the redux store array?

Tags:

reactjs

redux

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?

like image 912
rick1 Avatar asked Sep 20 '18 22:09

rick1


People also ask

Should I keep all component's state in Redux store?

There is no “right” answer for this. Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times. Others prefer to keep non-critical or UI state, such as “is this dropdown currently open”, inside a component's internal state.


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
    ),
};
like image 91
devserkan Avatar answered Oct 18 '22 20:10

devserkan