ahd786
ahd786

Reputation: 185

ComponentDidUpdate() causing memory leaks and drainage of battery in IOS

I am using componentDidUpdate() method for displaying updated data on screen whenever any functionalities is performed like scanning Qr code and storing data. But after searching on net I found that calling this.setState in componentDidUpdate() creates infinite loop. I tried to remove this problem through including prevState in the above method but I failed. Below is my code for more details. How can I update state coming from Asyncstorage without the help of componentDidUpdate()?

componentDidUpdate() {
    try {
      AsyncStorage.getItem('Data').then((value) => {
        this.setState({
          list: JSON.parse(value)
        })
      })
    } catch (err) {
    }
  }

Any help or suggestions would be helpful Thanks.

Upvotes: 0

Views: 553

Answers (1)

dentemm
dentemm

Reputation: 6379

Updating the state in componentDidUpdate will trigger another componentDidUpdate call, so you should restrict calling setState(). For example:

componentDidUpdate(prevProps, prevState) {

  // Only update state if list is empty 
  if (prevState.list.length === 0) {

    try {
      AsyncStorage.getItem('Data').then((value) => {
        this.setState({
          list: JSON.parse(value)
        })
      })
    } catch (err) {
    }
  }
}

Upvotes: 1

Related Questions