shes
shes

Reputation: 11

Redux: When removing specific element from array, it removes the last element instead

Im trying to remove an element from 'state' by using the filter function, which should remove the element from 'state' array at the index specified by 'action.index'. However it instead removes the last element from the 'state' array and I can't seem to figure out why it's doing it.

/reducer.js

import {
    ADD_ITEM,
    DELETE_ITEM,
} from './actions';

export default function addItems(state=[], action){
  switch (action.type) {
    case ADD_ITEM:
      return [
        ...state,
        action.item
      ]
    case DELETE_ITEM:
      return state.filter((_, i) => i !== action.index);
    default:
      return state
  }
}

EDIT

The above code works fine, it was a problem in another file that's removing the last element from the array.

Upvotes: 0

Views: 198

Answers (1)

Umesh
Umesh

Reputation: 2732

You can use splice instead of filter which is more precise to remove an item at specific index.

return state.splice(action.index,1)

The second param '1' means remove 1 item starting from action.index.

Upvotes: 1

Related Questions