In my react component I'm attempting to call the function emptyCart once a post request has been completed. However, when I call the emptyCart from inside the call back (Denoted in code as SECOND CALL), I get the error: TypeError: Cannot read property 'emptyCart' of undefined. When I call emptyCart from the beginning of the function, however, it works as expected. Sidenote, I don't ever have both calls of emptyCart in the code. Why can't I reference my component with this from inside the callback?
checkout = (order) => {
this.emptyCart(); //FIRST CALL
axios({
method: 'post',
url: '/api',
data: {
order:order,
},
})
.then(function(response) {
this.emptyCart(); //SECOND CALL
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}