Blog>
Snippets

Fetch and display async data before route navigation

Exhibit using the Vue.js 3 router's async 'beforeEnter' guard to fetch data before completing the route navigation, improving the SEO by ensuring content is loaded.
import { createRouter, createWebHistory } from 'vue-router';
import axios from 'axios';

const routes = [
  {
    path: '/some-path',
    name: 'my-route',
    component: () => import('./views/MyView.vue'),
    beforeEnter: async (to, from, next) => {
      try {
        const response = await axios.get('https://api.example.com/data');
        to.params.asyncData = response.data;
        next();
      } catch (error) {
        console.error(error);
        next(false);
      }
    }
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

export default router;
This JavaScript code creates a Vue Router with a `beforeEnter` guard. Before entering the route named 'my-route', it asynchronously fetches data from an example API using Axios. If the data is successfully fetched, it attaches the data to the route's params, thus allowing the component to access it via `this.$route.params.asyncData` once the route is navigated to. If an error occurs during the data fetch, it logs the error message and cancels the route navigation by calling `next(false)`, preventing the user from navigating to the route that depends on that data.