No More Posting New Topics!

If you have a question or an issue, please start a thread in our Github Discussions Forum.
This forum is closed for new threads/ topics.

Navigation

    Quasar Framework

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search

    How to import Vuex state to an external js

    Help
    4
    4
    2579
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • J
      jeimz173 last edited by

      Hi i am trying to import my Auth module’s state to an external js from my Store folder but, it returns undefined.

      my goal here is to include my token to my Api but Auth returns empty. and when i checked it out to my dev tools its not empty.

      // here is the external js (Api.js)
      import Vue from 'vue'
      import Auth from '../store/Auth'  // <- this returns an empty structure of my state
      
      export default () => {
        return Vue.prototype.$axios.create({
          baseURL: `http://localhost:3000/`,
          headers: {
            Authorization: `Bearer ${Auth.state.token}`
          }
        })
      }
      
      

      here is my store/index.js

      import Vue from 'vue'
      import Vuex from 'vuex'
      import createPersistedState from 'vuex-persistedstate'
      
      import Auth from './Auth'
      import Bank from './Bank'
      import Category from './Category'
      import Courier from './Courier'
      import Attribute from './Attribute'
      import Shop from './Shop'
      import Product from './Product'
      
      Vue.use(Vuex)
      
      const store = new Vuex.Store({
        strict: true,
        plugins: [
          createPersistedState()
        ],
        modules: {
          Auth,
          Bank,
          Attribute,
          Category,
          Courier,
          Shop,
          Product
        }
      })
      
      export default store
      
      

      Please help me thank you!

      1 Reply Last reply Reply Quote 0
      • G
        genyded last edited by

        Make your JS file a Quasar App Plugin. Those can directly access the store and you do not need to import anything:

        export default ({ app, router, store, Vue }) => {
            baseURL: `http://localhost:3000/`,
            headers: {
              Authorization: `Bearer ${store.Auth.state.token}`
            }
          })
        }
        

        That assumes you state is set up correctly. Don’t forget to add the plugin to quasar.conf.js. Also remember Vuex is not persisted across page refreshes by default.

        We use something like this with localStorage:

        import axios from 'axios'
        
        axios.defaults.baseURL = 'http://localhost:8000'
        axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
        
         export default ({app, router, Vue}) => { //<---NOTE YOU CAN ALSO ACCESS THE STORE HERE IF NEEDED AS IN THE ABOVE EXAMPLE
        
          // request interceptor - check auth
          axios.interceptors.request.use(function (config) {
            let token = false
            if (localStorage.getItem('ep-token') != null) { // auth check
              token = JSON.parse(localStorage.getItem('ep-token')).access_token
            }
            config.headers = Object.assign({}, { 'Authorization': `Bearer ${token}` }, config.headers)
            return config
          }, function (error) {
            // Do something with request error
            console.log('REQUEST ERROR:', error)
            return Promise.reject(error)
          })
        
          Vue.prototype.$axios = axios
        }
        

        So you can hopefully see that there are a few different ways to tackle this. Hope this at least helps get you going in the right direction.

        1 Reply Last reply Reply Quote 1
        • prashant
          prashant last edited by prashant

          I am new to quasar please let me know is there any better way to do it. I used vue-persistance module

          import Vue from "vue";
          import axios from "axios";
          
          const axiosInstance = axios.create({
            baseURL: "http://localhost:5000/",
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json"
            },
            timeout: 10000
          });
          
          export default ({ store }) => {
            axios.defaults.headers.common["Authorization"] =
              "Bearer " + store.state.token;
          };
          
          Vue.prototype.$axios = axiosInstance;
          
          // Here we define a named export
          // that we can later use inside .js files:
          export { axiosInstance };
          
          1 Reply Last reply Reply Quote 0
          • s.molinari
            s.molinari last edited by

            @prashant - Please start new threads. This one is old and your question isn’t even relevant to it.

            Scott

            1 Reply Last reply Reply Quote 1
            • First post
              Last post