Accepted answer


let tempgalleryList = this.state.galleryList.filter(item => !== file);
this.setState({ galleryList : tempgalleryList })

Since setState is async, this.state.galleryList will not be updated in each iteration of your map function, so the final updated state will only have one item filtered out instead of all selected items.


You can use the callback version of setState which uses the updated state instead:

this.setState(prevState => ({ 
  galleryList : prevState.galleryList.filter(item => !== file), 

Alternative solution

Instead of calling setState in every iteration, you can call it outside of your map function instead (though setState updates will be batched anyway so no significant performance improvement):

this.setState(prevState => ({ 
  galleryList : prevState.galleryList.filter(item => !prevState.mediaSelected.includes(, 

Other problems with your code

} else {
  this.state.mediaSelected.splice(this.state.mediaSelected.indexOf(, 1);

You are directly mutating your state here. Do this instead:

this.setState(prevState => ({ 
  mediaSelected: prevState.mediaSelected.concat( 

this.setState(prevState => ({ 
  mediaSelected: prevState.mediaSelected.filter(e => e != 

Related Query

More Query from same tag