[Vuejs]-How to access property from axios function in created in Vue

2๐Ÿ‘

โœ…

Your closures are using their own this context, which is NOT the context you want. Replace them with arrow functions like this in order to access the this context of the enclosing scope (that is, your component state):

axios.interceptors.request.use((config) => {
    this.isLoading = true;
    return config;
}, (error) => {
    this.isLoading = false;
    return Promise.reject(error);
});
๐Ÿ‘คAyrton

1๐Ÿ‘

The word this always refers to the immediate scope. When using it inside a function from axios object it loses reference to your component. The solution is to simply capture that reference in a new variable

  created() {
    var vm = this;
    axios.interceptors.request.use(function (config) {

      vm.isLoading = true;

        return config;
      }, function (error) {
        vm.isLoading = false;
        return Promise.reject(error);
      });

    axios.interceptors.response.use(function (response) {
        vm.isLoading = false;

        return response;
      }, function (error) {
        return Promise.reject(error);
      });
  }

As this is treated very differently in arrow and normal functions, refer to When should I use Arrow functions in ECMAScript 6? for better understanding.

๐Ÿ‘คVarun Agarwal

Leave a comment