0

I want to remove an item from a list in redux store(state) and it shows that the element is removed, but the rendered page still shows the element.

here's the reducer code:

   export default function todoApp(state=[],action){
        switch(action.type){
            case 'ADD_TODO':
                return [...state,action.item];
            case 'TOGGLE_TODOS':
                 const index = action.index;
                let newState = state.map((item) => (
                    item.index===index? {...item, done: !item.done}: item
                ));
                return newState;
            case 'REMOVE_TODOS':

                let removeFromState = state;
                for(var i=0;i<removeFromState.length;i++){
                    if(removeFromState[i].index===action.index){
                        removeFromState.splice(i,1);
                    }
                }
                return removeFromState;


            default:
              return state;    
        }
}

and in the component, I am putting the state into a list variable like this: - > const list = this.props.state;

and in the component , putting the elements to be displayed in the itemsArray variable. The list here, should not show the item, but it is showing it. so, what am I doing wrong here?

const itemsArray = list.map((item)=>{
     if(item.done){
       count+=1;
     }
     return (
     <div> <li 
      key={item.index}
      style={item.done?styleItem:null}
      onClick={(e)=> this.props.toggleTodos(e,item.index) }
      >{item.value} 
      </li>
       <span 
       style={removeStyle}
       onClick={(e)=> this.props.removeTodos(e,item.index)}
       >x</span>
       </div>
     )

   })
faraz
  • 2,603
  • 12
  • 39
  • 61

1 Answers1

1

I am answering my own question here, because i figured out from a comment that i was mutating the state. when I was doing let removeFromState = state; the removeFromState was just a reference to the original state and thus on using splice i was mutating it. the fix was to use

let removeFromState = [...state]; 

which copied the original state onto this variable and then I made changes to this variable and returned the new state and now it's working properly.

faraz
  • 2,603
  • 12
  • 39
  • 61