Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slice vs filter in redux delete action

From Redux documentation, I know, that we never should mutate state and that's why we should use concat and slice methods, so I ended up with following reducer(most of actions removed for simplification):

export default function blocks(state = [], action) {  
    switch (action.type) {
        case DELETE_BLOCK:
          var index = state.findIndex(e => e.id === action.blockId);
          return [...state.slice(0, index), ...state.slice(index + 1)];
        default:
          return state;
}

In my case I don't have index of element I want to delete, so can I use filter? Like this:

export default function blocks(state = [], action) {  
    switch (action.type) {
        case DELETE_BLOCK:
          return state.filter(e => e.id !== action.blockId);
        default:
          return state;
}
like image 244
Uriil Avatar asked Feb 07 '23 14:02

Uriil


1 Answers

filter does not mutate the state, it returns a new Array so there is nothing wrong here.

We try to avoid filter when we are dealing with immutable data since it always returns a new reference, breaking the reference equality check ===. But if you don't use this kind of reference by trying to return the previous state reference if you think the state didn't change (and I think you're not doing this, it's ok), you don't need to worry about using filter.

like image 100
Pierre Criulanscy Avatar answered Feb 09 '23 18:02

Pierre Criulanscy