Paulos3000 - 9 months ago 82
Javascript Question

# Redux reducer failing to remove array element

I'm having problems trying to get my reducer to work correctly in Redux. I'm new to Redux so I might be missing something simple, but I've played with it for a while and can't figure out what's going wrong.

Here is my process:

## Define argument:

First I define the index value that I need. When logged, this returns the correct number...

const thisCommentIndex = parseInt(comments.indexOf(comment))


## Function Call:

<div onClick={this.props.removeComment.bind(null, thisCommentIndex)}></div>


## Action:

export function removeComment(index) {
return {
type: 'REMOVE_COMMENT',
index
}
}


## Reducer:

function comments(state = [], action) {
switch(action.type) {
case 'REMOVE_COMMENT' :
console.log('removing comment with index of ' + action.index)
return [
...state.slice(0, action.index), // why isn't this working???
...state.slice(action.index)
]
default :
return state
}
return state;
}


When I
console.log('removing COMMENT with index of ' + action.index)
, it logs the action.index correctly, the integer I would expect. But the function doesn't remove the element as expected.

Strangely, if I simply pass the array index instead, it works fine (removes the array element). (I would just do this, but due to the way I have set up my app it won't work in this case).

Am I missing something here? Any help appreciated.

You're missing a +1...
return [