raklos
raklos

Reputation: 28545

Access vuex store from catch block

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

Upvotes: 1

Views: 443

Answers (2)

Ricardo Tavares
Ricardo Tavares

Reputation: 166

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);
      }
    });

Upvotes: 2

einarmagnus
einarmagnus

Reputation: 3592

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

Upvotes: 5

Related Questions