Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Difference between ComponentDidUpdate and SetState callback function

I’ve done some research about an error I got in my react native app

Warning: An update (setState, replaceState, or forceUpdate) was scheduled from inside an update function. Update functions should be pure, with zero side-effects. Consider using componentDidUpdate or a callback..

I’ve done research but I still can’t understand the difference between them. My theoretical idea is to remove an element from an array of objects, but when I use setState with a callback function I get the error. Can anyone point me in the right direction or show me an example of how I can use componentDidUpdate. The code example below works for now but I feel it could be improved on, and I believe that is why I’m getting my error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  Delete_Task = (e) => {
    this.setState(prevState => {
      const tasks = prevState.daily.filter(task => task.ID !== e);
      this.setState({daily: tasks});
    })
  }

>Solution :

You need to return the new state object instead of calling another setState inside the outer setState callback

change

this.setState({daily: tasks});

To

return {daily: tasks};
// OR 
return {...prevState, daily:tasks}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading