1

I have the ajax code below to call up my server to save some data. If the call is a success, I can pass data to another component through my Vuex store and perform some action. Where 'this' below is my Vue component.

this.$store.commit('appRoot/alertSuccess', "Witness saved!")

But if there is an error and I enter the catch block, then 'this' is null. Why is that and is there a way to get the data so I can call my Vuex store in the catch statement?

this.$store.commit('appRoot/alertError', "Couldn't save witness. IT has been notified.")

Here is the block where I'm using it. In the catch block, 'this' is null!

save() {
  axios.post('/Api/CallSomethingHere', {
    //pass some data here
  }).then(response => {
    // do some action here
    // Show success...
    this.$store.commit('appRoot/alertSuccess', "Witness saved!")
  }).catch(function(error) {
    // Show error;
    this.$store.commit('appRoot/alertError', "Couldn't save data. IT has been notified.")
  });
}
chuckd
  • 13,460
  • 29
  • 152
  • 331
  • 6
    Your catch does not have [an arrow function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) so it's not bound to the current component instance. Try `.catch(error=>{...stuff}` instead. – HMR Jun 14 '19 at 17:34
  • 1
    This might be of interest https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback – jspcal Jun 14 '19 at 17:35
  • thanks! Fridays are the worst! – chuckd Jun 14 '19 at 17:40

0 Answers0