I am currently working with a django-rest-axios-vuejs application stack, and I have a specific task that involves the vue-router
.
Within the beforeEach
guard of the vue-router
, I am checking permissions by verifying something in the me
object within the vuex store. While everything functions correctly, there is an issue when the page is refreshed.
Upon refreshing the page, the vuex store gets cleared, causing my beforeEach
function to attempt checking the now empty me
object in the store.
My goal is to retrieve the me
object from the API if it is not present in the store. However, due to the asynchronous nature of fetching data, the hasPermission()
method executes before the API call is completed.
I attempted using the await
keyword before the API call, but it did not yield the desired result.
This is my
beforeEach
guard :
router.beforeEach(async (to, from, next) => {
const isLoggedIn = getIsLoggedIn()
handleLoggedInStatus(isLoggedIn)
if (to.meta.requiresAuth) {
if (isLoggedIn) {
if (to.meta.permission) {
if (!store.state.me) await store.dispatch('FETCH_ME')
hasPermission(to.meta.permission) ? next() : next({ name: 'HomePage' })
} else {
next()
}
} else {
next({ name: 'LoginForm' })
}
} else {
next()
}
})
This is my action from the store :
actions: {
FETCH_ME: (state) => {
http
.get('base/users/me/')
.then(response => {
state.me = response.data
})
.catch(error => {
console.log(error)
})
}
}
To overcome the timing issue, I found a workaround:
function sleep (ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
router.beforeEach(async (to, from, next) => {
const isLoggedIn = getIsLoggedIn()
handleLoggedInStatus(isLoggedIn)
if (to.meta.requiresAuth) {
if (isLoggedIn) {
if (to.meta.permission) {
if (!store.state.me) {
store.dispatch('FETCH_ME')
await sleep(2000)
}
hasPermission(to.meta.permission) ? next() : next({ name: 'HomePage' })
} else {
next()
}
} else {
next({ name: 'LoginForm' })
}
} else {
next()
}
})
In this setup, we introduce a brief delay of "random" (2 seconds) using a small sleep()
method.
As someone who is relatively new to using async
and await
, I wonder what I might be missing to make await store.dispatch('FETCH_ME')
function properly?
Any guidance on this matter would be greatly appreciated. Thank you in advance :)