Search code examples
javascriptvue.jsaxiosvuexvuex-modules

Access vuex state in separate axios template js file


I have a problem. I have a Vuex state. Also I am making axios request. I have created a separate file for template axios request with predefined header. It looks like this:

import axios from 'axios'
import store from '../store/index'

export default axios.create({
  baseURL: 'https://k-3soft.com/',
  timeout: 1000,
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${store.getters.getToken}`
  }
})

The problem is that in this case store in undefined. So how can I import to this /src/axios/request.js file my vuex store? Also I have tried import { store } from '../store/index'. My store looks like this:

import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'

Vue.use(Vuex)

export default new Vuex.Store({
  namespaced: true,
  modules: {
    user
  },
  state: {
    url: 'https://icfprod.k-3soft.com/',
    token: '',
  },
  getters: {
    getToken: state => state.token
  },
})

Also may by anyone can share to view any repository where there is Vuex with modules, axios with file with separate predefined template. Just wanna see how to organize my project's structure. Thanks everyone for help.


Solution

  • Use a factory function to create the axios instance.

    // request.js
    import axios from 'axios'
    
    const createAxiosInstance = (token) => {
      return axios.create({
        baseURL: 'https://k-3soft.com/',
        timeout: 1000,
        headers: {
          'X-Requested-With': 'XMLHttpRequest',
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        }
      }
    })
    
    export default createAxiosInstance
    

    Then use it in a module like:

    // user.js
    import createAxiosInstance from '../request.js'
    
    
    const userModule = {
      // ...
      actions: {
        async doSomeAction ({ state, commit, rootState }) {
          const axios = createAxiosInstance(rootState.token)
    
          const response = await axios.post('/some/api/endpoint')
            .then(response => response)
            .catch(error => {
               // handle error
            })
    
          commit('SOME_MUTATION', response.data)
        }
      }
    }