After successfully logging in, I store the user key in localstorage and redirect the user to the dashboard. However, my application does not utilize the stored key until after a manual refresh.
Below is the code snippet responsible for setting the key:
axios.post(url, creds)
.then((response) => {
if (response.data.code === 401) {
context.error = response.data.data
} else {
Vue.ls.set('id_token', response.data.data.key, 60 * 60 * 1000)
this.user.authenticated = true
}
}).catch((err) => {
context.error = err.data
})
Interestingly, there is a route guard function in place that correctly accesses the value right after login without needing a refresh:
router.beforeEach((to, from, next) => {
const r = axios.create({
baseURL: env.api_url,
timeout: 25000,
headers: {
'Authorization': 'Bearer ' + Vue.ls.get('id_token'),
'X-Requested-With': 'XMLHttpRequest'
}
})
if (to.name === 'Login') {
r.get('user').then(() => {
next({name: 'Dashboard'})
}).catch(() => {
next({name: 'Login'})
})
}
if (to.name !== 'Login') {
r.get('user').then(() => {
next()
}).catch(error => {
console.log(error)
next({name: 'Login'})
})
} else next()
})
Why is this issue occurring?