Uncaught (in promise) TypeError: Cannot read property of undefined ReactJS

We got into this issue when we were working on ReactJS application. We were calling an external API and the API was returning a promise. When the promise was resolved we wanted to call a method using special object this. See the code segment.

getAPIData() {
    fetchFactory('/url', 'GET')
        .then(function (data) {            
            this.displayAPIData(data);    
        })
}
// Uncaught (in promise) TypeError: Cannot read property of undefined

Reason of the issue

The scope of the special object this limited to the callback function, it does not have displayAPIData method defined. We need to use the arrow function to get the proper context.

Solution of the issue

getAPIData() {
    fetchFactory('/url', 'GET')
        .then(data => {            
            this.displayAPIData(data);    
        })
}
Share