Search code examples
vue.jsaxiosvuex

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


Solution

  • 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