0

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.

2
  • 1
    Have you tried logging the value of action.index? Maybe this has the wrong value for some reason. Commented Jul 30, 2017 at 14:11
  • 2
    Works fine for me: jsfiddle.net/u9ma1c4p Commented Jul 30, 2017 at 14:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.