Accessing vue-axios inside Vuex module actions

Viewed 1901

In my Vuex setup, the store is currently structured like this:

store
 - modules
   - common_data
     - index.js
     - mutations.js 
     - actions.js 
     - getters.js

Now, one of the actions inside actions.js is defined as:

populateTimeZones(context) {
    var baseUrl = context.getters.getApiBaseUrl;

    this.$http.get(baseUrl + '/time-zones')
    .then(function (res){
        if(res.status == 'ok'){
            this.$store.commit('SET_TIME_ZONES', res.info.timeZones);
        } else {
            alert('An error occurred. Please try again!');
            return;
        }
    }.bind(this));
}

I think the Vue instance is not available here, which is causing the action to fail with the error: Cannot read property 'get' of undefined. I've tried other combinations like this.axios and vue.axios but the result is same.

Am I doing something wrong? What is the common pattern for handling such cases?

1 Answers

You won't be able to access the Vue instance without passing it through or creating a new one.

A simple way to do what you want is to simply pass your this through to your action this.$store.dispatch('populateTimeZones', this), then change your method signiture to populateTimeZones({ context }, vueInstance). This would then allow you to access vueInstance.$http.

Another idea would be something called vue-inject which is a DI container for Vue. It would allow you to register axios as a service and then simply call VueInjector.get('axios') whenever you need it. On the Vue component itself you can do dependencies: ['axios'] and then use like this.axios. Not so much an issue in this case but helpful when you have lots of services doing work for you

Related