'How can i make sure a vuex action has finished before the page loads
I have 2 issues where i pull data from an api and use it. However, the page loads before the api request has completed. My first problem is in the router. I have a requiresAuth, to check if i'm logged in, i have the following: router:
router.beforeEach((to, from, next) => {
if (!to.matched.some(record => record.meta.requiresAuth)) return next(); // does not require auth, make sure to always call next()!
if (store.getters.isLoggedIn) return next();
store.dispatch('pullUserInfo').then(() => {
if (store.getters.isLoggedIn) return next(); // logged in, move it
next({
path: '/login',
{ redirect: to.fullPath } // save the location we were at to come back later
});
});
});
store action:
pullUserInfo(context) {
fetch(`${process.env.VUE_APP_API_ENDPOINT}/v3/user`)
.then(async r => {
if (r.status !== 200) return context.commit('setUserInfo', null);
const json = await r.json();
context.commit('setUserInfo', json);
});
},
app constructor:
createApp(App)
.use(router)
.use(store)
.mount('#app-mount');
When refreshing, checking in devtools, my userInfo object has data. However this data is set after router.beforeEach checks
My second issue is similar. I populate a table with data from the store, however when refreshing the store value is null
because the api request is still ongoing
How do i wait for my action to complete and assure data is present before continuing? I am using the latest vuex, vue-router and vue3. Working with SFC's and initialized with vue cli
Solution 1:[1]
Returning fetch()
's promise did the trick.
This answer was given in the official Vue Discord server
pullUserInfo(context) {
return fetch(`${process.env.VUE_APP_API_ENDPOINT}/v3/user`)
.then(async r => {
if (r.status !== 200) return context.commit('setUserInfo', null);
const json = await r.json();
context.commit('setUserInfo', json);
});
},
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Maxim |