0

I have a class component, called ListOfItems.js, that lists a bunch of objects like so (btw, I am required to use class components, not function components):

class ListOfItems extends Component {
  construction (props) {
    super(props);
    this.state = {
      objectList: []
    }
  }
}

// This gets the list of objects to display
componentDidMount() {
   this.getObjectList();
}

componentDidUpdate() {
  //not sure what to put for "previous ObjectList"
  if( this.state.ObjectList !== previous ObjectList) {
     this.getObjectList();
  }
}

Inside of Object.js (the file for each object displayed in ListOfItems), I have a delete functionality, where if the user selected the "x" icon on the object, that object is deleted from the list. An instance of the Object.js inside of ListOfItems.js looks like this:

// BTW, I cannot change anything here. I have simplified
// my code very heavily for this purposes of this question.
{this.state.objectList.map(item) => {
  <Object 
    objectList={this.objectList}
    data={item}
    //few other props here
  >
}

I can see that the object is removed right after I click on "x", as per the api fetch response that I console logged. And when I refresh the page manually, the object is removed from the list displayed.

GOAL: I want the removal to happen in real time, right after the user clicks "x".

penguin
  • 143
  • 3
  • 11
  • what is `this.state.marObjectList `? is it a typo and you meant `this.state.objectList`? – Georgy Nov 11 '21 at 19:31
  • What props do you have in `Object`? Does it provide some `onDelete` callback? – BANO notIT Nov 11 '21 at 19:31
  • @Georgy Yes, fixed. – penguin Nov 11 '21 at 19:41
  • easiest way to check for an array `length`: `if( this.state.objectList.length !== previous.objectList.length) { this.getObjectList(); }`. Also you could use `onDelete` callback as @BANOnotIT mentioned and do not use `componentDidUpdate` – Georgy Nov 11 '21 at 19:43
  • @BANOnotIT I have edited the question to include the props. I have not provided a callback in `onDelete`. I am not sure how this work. I need to have another function inside of `onDelete` that would rerender the parent `ListOfItems.js` page, correct? How would I do this? – penguin Nov 11 '21 at 19:51
  • @Georgy, thanks for your response. I am not sure how to get the previous `objectList`. Is `previous.objectList.length` an actual usable statement? Is the `this.state.objectList.length` immediately decremented upon deleting the object, even if it is not reflected on the UI? – penguin Nov 11 '21 at 19:54
  • I resolved this issue. The only problem is that componentWillUpdate keeps getting called infinitely, even though I have a conditional inside of it and the state changes only once. I have updated my code above. – penguin Nov 12 '21 at 15:58

0 Answers0