TransWikia.com

Remove item from state

Stack Overflow Asked by Clayton Crockville on December 5, 2020

I know this question has been asked a lot but I haven’t seem to find a solution even tho I’ve tried different scenarios.

this.state = {
      chartTypes: [{name: 'Bar', id: 1},{name: 'Line', id: 2},{name: 'Pie', id: 3},{name: 'Radar', id: 4} ],
      selectedChart: [],
}

  onSelect = (selectedList, selectedItem) => {
   // selectedItem.name returns name of chartTypes, selectedItem.id returns id of chartTypes.

    this.setState({
      selectedChart: selectedItem.name
    })
  }
  
  onRemove = (selectedList, removedItem) => {
       // removedItem.name returns name of chartTypes, removedItem.id returns id of chartTypes.
  }

The select option works fine but I just put it there so you can have a better understanding. onSelect puts every selectedItem.name into selectedChart. On the remove function, how may I remove item from this.state.selectedChart based on the value/index.

3 Answers

Just filter and set backed to state

onRemove = (selectedList, removedItem) => {
      let filtered = this.state.chartTypes.filter(list=> list.id !==removedItem.id);
      this.setState({ chartTypes: filtered });
  }

Answered by Vahid Akhtar on December 5, 2020

I think you can do something like this

    let temp = this.state.selectedChart;
    temp=temp.filter((item) => item !== removedItem.name);
    this.setState({ selectedChart: temp });

Answered by Ahmad Suddle on December 5, 2020

var newArray = this.state.selectedChart.filter((el)=> 
  el.id !==removedItem.id
);

after filter

this.setState({selectedChart:newArray})

Answered by Yoel on December 5, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP