Search code examples
nuxt.jsvuex

Vuex with nuxtjs access store from JS file


I have a JS file called axios.js and I'm using interceptors to get the available languages from every API call I make, and store the available languages in an array called comingLangs[] My question is how can I store this array inside my store so I can use it in my nuxt project? the import {store} from './store' does not work I get an error : Cannot find module './store'

here is my code :

plugins/axios.js

import {store} from './store' //Not working
export default function ({$axios, i18n}, inject) {
  let comingLangs=[]
  const apiClient = $axios.create({
    headers: {
      'X-localization': i18n.locale,
    }

  });
 
  inject('apiClient', apiClient);
  apiClient.interceptors.response.use(function (response) {
    //Check if the response has meta_tags
    if (response.data.content.meta_tags !== undefined && response.data.content.meta_tags) {
      // store the languages from response to an array
      comingLangs = Object.keys(response.data.content.meta_tags.alternative)
     
      store.commit("SET_AVAILABLE_LANGUAGES",comingLangs)  // here is where I want to store comingLangs
    }
    return response
  });
}

store/index.js

export const state = () => ({
  availableLanguages: [],
})
export const mutations = {
 SET_AVAILABLE_LANGUAGES(state, payload) {
    state.availableLanguages = payload
  },
}

Solution

  • Finally, I have been able to solve it by passing app as an argument to my function and using store from app like this :

    export default function ({$axios, app, i18n}, inject) {
      let comingLangs=[]
      const apiClient = $axios.create({
        headers: {
          'X-localization': i18n.locale,
        }
    
      });
     
      inject('apiClient', apiClient);
      apiClient.interceptors.response.use(function (response) {
        //Check if the response has meta_tags
        if (response.data.content.meta_tags !== undefined && response.data.content.meta_tags) {
          // store the languages from response to an array
          comingLangs = Object.keys(response.data.content.meta_tags.alternative)
         
          app.store.commit("SET_AVAILABLE_LANGUAGES",comingLangs)  
        }
        return response
      });
    }