0

I have a componentDidMount where I am calling an API and then have a this.setState({...this.state}).

Inside render, I have a button that calls delete function. Now when this delete is called I am re-rendering but I also want this API that is present in componentDidMount to be called because the delete functionality deletes some data in the same component, which should show updated value later.

The problem is, when I reload the page I get the data required but re-rendering does not show the required data.

2
  • When the item is deleted you need to setState again with new state for component to show updated items. Commented Oct 30, 2018 at 10:41
  • It would be better to see the actual code in addition to the description of the code. Commented Oct 30, 2018 at 10:43

2 Answers 2

1

Practically the API call code that you write in componentDidMount could be written as a separate function which you can then call, when you delete the data.

componentDidMount() {
    this.fetchData();
}

// using arrow function to achieve correct context binding
fetchData = () => {
   // your API call here
} 

delete = () => {
   // call fetchData here after delete
   this.fetchData();
}
Sign up to request clarification or add additional context in comments.

1 Comment

I agree with @Shubham Khatri. Here is how i fixed this issue. stackoverflow.com/questions/54892155/…
0

if your react version is going to be less than 16 , then you can us componentDidUpdate for that. This is been deprecated but still you can use UNSAFE_ flag before its name.

check this link from stackoverflow itself for a real world example: here

if you want to use a more robust way of handling that in react version 16 and above you could use getDerivedStateFromProps , for that you can check the corresponding way of handeling it from stackoverflow: here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.