Update State in a Class Component

Advertisements
private readonly maxSizeOfDownloadedFiles: number = 1000000;

state = {
  totalSum: this.maxSizeOfDownloadedFiles
};

handleCallback = () => {
  this.setState({ totalSum: 12 })
  alert('totalSum ' + this.state.totalSum);
};

When I run handleCallback method it doesn’t update totalSum and gives me the default value, alert show totalSum 1000000 not 12. So why setState doesn’t work?

>Solution :

You can use the callback method in setState({} ,() => {}) which gets called immediately after the state update.

private readonly maxSizeOfDownloadedFiles: number = 1000000;

state = {
  totalSum:  this.maxSizeOfDownloadedFiles
}

handleCallback = () => {
  this.setState({ totalSum: 12}, () => {
   alert('totalSum ' + this.state.totalSum);
 })
}

Leave a ReplyCancel reply