0
export class News extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      news: [],
    }
    this.deleteSingleNews =this.deleteSingleNews.bind(this)
  }


  componentDidMount() {
    fetch('/getNews').then((response => response.json())).then(result => {
      console.log('what?')
      this.setState({ news: result })
    })

  }

  deleteSingleNews(id) {
    const news = this.state.news.filter(i => id !== i._id)

    this.setState({news:news})
  }
  render() {
    return (
      <Container>
        <Row>
          {this.state.news
            ? this.state.news.map((item, index) => (
              <Col xs={12} md={6}>
                <Thumbnail
                  props={item} deleteItem={this.deleteSingleNews}
                  key={index}
                />
              </Col>
            ))
            : (<span>no data</span>)}
        </Row>
      </Container>
    )
  }
}

This is being called from child component:

const decision =()=>{
      this.props.deleteItem(this.state._id)
      handleClose();
    }

deleteSingleNews is passed as an props to it's child component and gets executed when used clicks a button as decision. Id is passsed to the function deleteSingleNews(id) where the state is set to get rid of that particular item, right item is being removed from the array this.state.news, but the problem is view renders that the last from list is being removed.

Also, if i console log length after item removal this.state.news.length it shows the original length, unless i console log it in callback.

  • Can you try by making that news as a variable instead of a const in your delete function. – Adesh Kumar Jun 02 '20 at 17:29
  • There may be some other code that may cause the problem like `Thumbnail`, please make a reproducible example, you can use [codesandbox](https://codesandbox.io/s/vanilla-react-template-irhcq) for making a demo. – Dennis Vash Jun 02 '20 at 17:31
  • Also note that your conditional rendering is useless, as `this.state.news` is always `true`. – Dennis Vash Jun 02 '20 at 17:31
  • Make sure the ```Thumbnail``` component calls ```deleteSingleNews``` with the right id. The second problem is easy, setState is an async function. So it will not execute right away, just at the next render. – Peter Ambruzs Jun 02 '20 at 17:32
  • Its because you are not using the unique index refer to [https://stackoverflow.com/questions/43642351/react-list-rendering-wrong-data-after-deleting-item/47116380#47116380](https://stackoverflow.com/questions/43642351/react-list-rendering-wrong-data-after-deleting-item/47116380#47116380) – Saqy G May 28 '21 at 13:54

0 Answers0