1

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);
      });
  }
3
  • you're inside a callback function, this is no longer your component Commented Jul 12, 2017 at 20:57
  • Ah, didn't realize it worked like that. Do you have a workaround that you recommend? Commented Jul 12, 2017 at 20:58
  • yeah i added an answer Commented Jul 12, 2017 at 20:59

1 Answer 1

3

this is referring to the callback function. A simple fix would be to replace with an arrow function.

checkout = (order) => {
this.emptyCart(); //FIRST CALL

axios({
  method: 'post',
  url: '/api',
  data: {
    order:order,
  },
})
.then((response) => {
  this.emptyCart(); //SECOND CALL
  console.log(response);
})
.catch(error) => {
  console.log(error);
});

}

Sign up to request clarification or add additional context in comments.

1 Comment

@PatrickConnors i'd recommend reading up on the this keyword in js, will save you some future headaches

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.