Vue 3 and Router 4 - useRoute sometimes is undefined in onMounted hook
Not sure if many of you are aware that I also work on development projects as an architect. Almost all the web projects we did recently used Vue as the framework for front-end development. Recently, we ran into an issue when using Vue 3 and Router 4 and would like the findings here with you.
Referring to the below code.
import { ref, onMounted, inject, watch } from "vue";
import { useRoute } from "vue-router";
const route = useRoute();
onMounted( () => {
if (route.params && route.params.id) {
}
});
The purpose of the above code is to read the ID from the URL and use it to load some data from the backend API. However, we find some sometimes, the page will fail to load the information and when checking the console logs in browser, it will report route.params failed as the route is undefined. If we refresh the page now, it will just work.
After some checking and searching the web, we realize the issue is because when onMounted hook is executed, the router component has not yet completed initialization and hence the result from useRoute()
is undefined (a.k.a null).
To resolve the issue, we changed the code a bit to below.
import { ref, onMounted, inject, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
onMounted(async () => {
await router.isReady();
if (route.params && route.params.id) {
}
});
The key difference is that now the handler for onMounted is async and allows us to use await. Then we will call the router.isReady()
and await it before moving next. After implementing this change, all the unable load data issue is gone and the application always working as expected.
FYI, we do not experience this when using Vue 2 and Router 3. Believe this should be something to do with Vue 3.