Reputation:
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 true and false without a problem.
console.log('about to set false')
this.setState({
loadingMedications: false
});
console.log('about to set true')
this.setState({
loadingMedications: true
});
SAIIndexedDB(response.data).then(function(result){
this.setState({
loadingMedications: false
});
})
.catch(function(error){
console.log('error', error);
});
So above the console writes out fine and no error but then in the promise , the catch throws the error - It takes about a minute for this promise to return as it is loading 170k records into an offline indexeddb database and then returns and thus that loadingMedications is a loading spinner that needs to be set to false in order to hide it.
Thoughts on why ?
Upvotes: 0
Views: 78
Reputation: 86
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 $self
self.setState({
loadingMedications: false
});
})
.catch(function(error){
console.log('error', error);
});
Upvotes: 0
Reputation: 20765
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
});
})
Upvotes: 2