'How to wait for the middleware to finish before loading the page
I am on Vue2 and Nuxt. I want ended my requests in middleware before load page. How create that ? How can I wait for the end of my request before loading my page?
export default ({ store }) => {
fetchTest(store, Authorization);
};
async function fetchTest(store, Authorization) {
return await axios
.get("/test", {
headers: {
Authorization,
},
})
.then(res => {
// somethings...
})
.catch(err => {
console.error(err)
});
};
Solution 1:[1]
You can do this either in the route middleware or directly in the router hook beforeEach
Like here:
router.beforeEach(async (to, from, next) => {
if (needToFetch) {
await fetchTest()
}
next()
})
Look here Route Guard -> Navigation Guards
Or you can run your code in a hook created by the main component and handle the rendering of your content with the specified flag
Example:
<template>
<div v-if="loading">loader</div>
<div v-else>content</div>
</template>
<script>
export default {
data() {
return {
loading: true
}
},
async created() {
await fetchData()
this.loading = false
}
}
</script>
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 | Ilya Degtyarenko |