How to access state outside export in store/index.js?

Viewed 230

I use Axios in my store actions and wish to set an Axios header based on some state(to change the request header for accepted languages). When trying to access the store outside the export, I get an error "cannot find property state of undefined". My store/index.js file:

import Vue from "vue";
import Vuex, { Store } from "vuex";
import Axios from "axios";
Vue.use(Vuex);

Axios.defaults.headers['Accept-Language'] = store.state.Lang

const store = new Vuex.Store({
  state: {
    Lang: "en",
    ApiConf: [],
    Token: null,
    Session: null,
  }
...
}
export default store

How would you access the store and state in the same file where the store is defined? Or how would you go about implementing this state-dependent Axios header without going into the store and defining for every action?

2 Answers

The problem with your code is that you access the store variable before declaring it, hence the error.

Move the line:

Axios.defaults.headers['Accept-Language'] = store.state.Lang

above the export statement:

import Vue from "vue";
import Vuex, { Store } from "vuex";
import Axios from "axios";
Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    Lang: "en",
    ApiConf: [],
    Token: null,
    Session: null,
  }
...
}
Axios.defaults.headers['Accept-Language'] = store.state.Lang

export default store

store isn't defined at the time when it's accessed. Vuex store is commonly defined in separate module, so it's already available in a module where it's imported and doesn't cause race conditions.

Another problem is that the reactivity cannot be preserved when Axios.defaults.headers is assigned once with store value, Accept-Language will always be initial value, unless it's specified in request headers.

This should be done in Axios interceptor instead:

Axios.interceptors.request.use(config => {
  config.headers['Accept-Language'] = store.state.Lang;
  return config;
});
Related