1

In mounted function i create an action which fetch data from Rest Api to my table in vuejs componeny

mounted() {
    UserService.getProjects().then(
      (response) => {
        this.isProject = true;
        this.projects = response.data;
      },
      (error) => {
        this.isProject = false;
      }
    );
}

but, when i click on my menu on route to this page, I'm redirected to this page in one second, but my data is still loading and at the beginning i have an empty table..., how to fetch data and then redirect to this page? thanks for any help

ps. i use router-link to navigate to another page

2
  • Have you tried using async and await in mounted hook? Commented Feb 14, 2021 at 17:09
  • @YashMaheshwari no, can you give an example?
    – markWanka
    Commented Feb 14, 2021 at 17:13

2 Answers 2

2

To answer your exact question, you can have a look at Navigation Guards.

In your router, do something similar

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        UserService.getProjects().then(
          (response) => {
            // update store or some state
            next()
          },
          (error) => {
            // update store or some state
            next(false); //cancel or handle the error
          }
        );
      }
    }
  ]
})

But you probably don't want to delay the route transition until the data loads. Instead you want to show a loading state until the data is ready. So you would just handle that in your template and existing mounted function, the way you've done.

By blocking the navigation, you'd have to decide what to do when the data fails to load

0
-1

You can try using async and await on the mounted hook.

async mounted() {
    await UserService.getProjects().then(
      (response) => {
        this.isProject = true;
        this.projects = response.data;
      },
      (error) => {
        this.isProject = false;
      }
    );
}

Or you can also use Promise.

async mounted() {
    await Promise.all(
    UserService.getProjects().then(
      (response) => {
        this.isProject = true;
        this.projects = response.data;
      },
      (error) => {
        this.isProject = false;
      }
    );)
}
2
  • It's not work in my project :/ I think that I need to use beforeMount of somethine else
    – markWanka
    Commented Feb 14, 2021 at 17:21
  • You can try one of three things: beforeCreate, created or asyncData in place of mounted hook Commented Feb 14, 2021 at 17:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.