0
votes

Im trying to put error messages from an api call and put it in the vuex store, but im not sure how to do it.

I have this in a "method" within a vue file

 axios
    .post("/api/model", this.model)
    .then(response => {
      window.location.href = "/Home/Index";
    })
    .catch(function(error) {
      if (error.response) {
        this.$store.commit("setServerErrors", error.response.data);
      }
    });

Im getting the following error: Uncaught (in promise) TypeError: Cannot read property '$store' of undefined

2
change the function to a arrow one, you are losing the this scopeMunteanu Petrisor

2 Answers

4
votes

Probably your function is reassigning the value of this.

Try changing it to:

axios
    .post("/api/model", this.model)
    .then(response => {
      window.location.href = "/Home/Index";
    })
    .catch(error => {  // <= HERE IS THE CHANGE!!
      if (error.response) {
        this.$store.commit("setServerErrors", error.response.data);
      }
    });

Read about the difference between function(arg) {}and (arg) => {}here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

1
votes

You are using a function instead of an arrow function on the catch block so this inside that block has a different scope.

Just replace the function with an arrow function.

axios
    .post("/api/model", this.model)
    .then(response => {
      window.location.href = "/Home/Index";
    })
    .catch((error) => {
      if (error.response) {
        this.$store.commit("setServerErrors", error.response.data);
      }
    });