Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why splice not working correctly in react?

I am trying to delete row from my list using delete button .I do like this

if (state.indexOf(action.payload) > -1) {
      console.log('iff----')
        state.splice(state.indexOf(action.payload), 1);
    }
          console.log(state)

     return state

but it is not deleting the row .here is my code https://plnkr.co/edit/bpSGPLLoDZcofV4DYxPe?p=preview Actually using add button I am generating the list of item and there is delete button I am trying to delete item from list using delete button could you please tell me why it is not working ?

like image 828
user5711656 Avatar asked Jan 02 '17 00:01

user5711656


1 Answers

Avoid using Array#splice when working with state in React or Redux. This mutates your state, which you never want to do. Instead, favour immutable methods like Array#slice. e.g.

const index = state.indexOf(action.payload);
if (index === -1) {
  return state;
}
return state.slice(0, index).concat(state.slice(index + 1));

In ES6 that last line could also be written as:

return [...state.slice(0, index), ...state.slice(index + 1)];
like image 167
David L. Walsh Avatar answered Oct 03 '22 15:10

David L. Walsh