How to access Vuex from Axios boot files
-
I store my JWT tokens in vuex module (user) and I have a axios request interceptor that I use to populate the Brarer token in the request head.
In vanilla Vue, I would simply import the store and then access my module state
import store from '../store/index' var token = store.state.user.token
When I try to do this from axios.js in Quasar it does not work. Can anybody help.
A point to note, mapState in Vue files works just fine, so I’m 99.9% sure vuex is configured correctly.
-
If you work inside the default function of the boot file, the
store
is injected and you can use it. It should be your instantiated store.https://quasar.dev/quasar-cli/boot-files#Introduction
https://quasar.dev/quasar-cli/boot-files#Quasar-App-FlowScott
-
@s-molinari Thanks Scott. I have already tried that approach. I can see the modules when I inject store, but I can not access any of the variables within State or any of the methods in actions or mutations. For example in the user module I have
state: { user: { firstname: 'John', lastname: 'Smith', email: 'jsmith@example.com' }, token: { token: 'xxxxx', refresh_token: 'xxxxxxxx' } }
Through injected state in
axios.js
I can’t get below the base variablesuser: { obj:..., proto: ....}, token: {obj: ...., proto: ....)
For now, I have worked around it by writing my token to LocalStorage, which I can access from axios.js, but I want to get this fixed, so everything is accessed through the store.
Simon
-
@ioncoder use something like vuex-persistedstate.
-
@metalsadman Thank you. You know I always use that when using vanilla Vue, I don’t know why I didn’t already try that. I think it might be because Quasar does so much for you (which is great), but you start to stop thinking for yourself sometimes.
I will give it a try
Simon -
Is that the issue? Getting a token stored and persisted to bridge browser sessions?
Scott
-
@s-molinari @metalsadman Thank you, Yep, That solved it. I was coding from 7am till 1am yesterday so I will give myself a break (this time), still feel like a bit of an idiot though.
Thanks for your help.
Simon