[Vuejs]-Access vuex state in separate axios template js file

0👍

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)
    }
  }
}

Leave a comment