Skip to content Skip to sidebar Skip to footer

React App Is Throwing Error Cannot Read Property 'setstate' Of Undefined In Nested Promise

Getting this error in my React application inside nested promise calls Cannot read property 'setState' of undefined Strange to me is outside of the promise setting value to both

Solution 1:

The issue is with this.

Instead of this,

SAIIndexedDB(response.data).then(function(result){
    this.setState({
         loadingMedications: false                    
    });  
})

you need to use arrow function which auto binds this,

SAIIndexedDB(response.data).then((result) => {
    this.setState({
         loadingMedications: false                    
    });  
})

Solution 2:

Another solution is assigning this to a variable and use that variable in callback

const self = this;
SAIIndexedDB(response.data).then(function(result){
    // replace $this with $selfself.setState({
         loadingMedications: false                    
    });  
})
.catch(function(error){
    console.log('error', error);
});

Post a Comment for "React App Is Throwing Error Cannot Read Property 'setstate' Of Undefined In Nested Promise"