Home > OS >  How to trigger parent componentDidUpdate by click in child component
How to trigger parent componentDidUpdate by click in child component

Time:11-14

In my parent component, I have a class component called ListOfItems.js, that lists a bunch of objects like so:

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

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

componentDidUpdate(_prevProps, prevState) {

  if( this.state.ObjectList !== prevState.ObjectList) {

     // this is called infinitely which is a problem
     console.log("entered");
     this.getObjectList();
  }
}

getObjectList = () => {
  const input = { id_for_this_list: id }

  fetch( connectToApi, {
     method: "PUT",
     headers: { //stuff}
     body: JSON.stringify(input)
  })
     .then(res => //)
     .then(result => 
        if( result.length >= 0) {
            this.setState( {...this.state, objectList: result });
        }   
     )
     .catch(err=>{console.error(err)});
}

render () {
  return (
    {this.state.objectList.map(item) => {
      <Object 
        objectList={this.objectList}
        data={item}
       //few other props here
      >
    }}
  )
}
     

In my child component, I have a functional component called Object.js. In this, I have a delete functionality, where if the user selected the "x" icon on the object, that object is deleted from the list.

// 'x' image that, when clicked on, deletes object from list of objects
// (heavily simplified for stackOverFlow)

<img onClick= {() => { deleteObject() })>

const deleteObject() = () => {
   fetch( connectToApi, {
     method: "DELETE"
   })
      .then(res => //)
      .then(result => //deletion made and confirmed succesful)
      .catch(err => console.error(err))
}

How do I trigger the componentDidUpdate() in ListOfItems.js (parent), when I click on the "x" on an Object (child)?

Btw, the parent must be a class component and the child must be a functional component, unfortunately.

CodePudding user response:

You never appear to set the state for your parent component when you call getObjectList so that could be an issue for you, I'm not sure if you're left it out of this excerpt on purpose.

Either way, you'll need to pass down a function from the parent component that sets the state held in the parent component. That will cause the parent to rerender.

If you don't want to change the state you can potentially call a function that you pass from the parent that forces a refresh, but this wouldn't be ideal.

parentResetFunction = () => {
   this.forceUpdate()
}
  • Related