How To Ensure Vue Main Template Create Method Finishes Before Router-View Inner Template Create Method Starts

55 Views Asked by At

I have a simple setup with a main Vue template like this:

<template>
  <div>
    [Other code here...]
    <v-app style="overflow-y:hidden">
      <router-view class="view"></router-view>
    </v-app>
  </div>
</template>

<script>
export default {
  methods: {
    created() {
      //I NEED THIS CODE TO FINISH FIRST BEFORE ROUTER-VIEW 
      //TEMPLATE CREATED METHOD STARTS
      await XxxService.xXXxXX()
          .then((response) => {  
            localStorage.mySpecialVariable = yyyyy;
          })
          .catch(() => {

          });
    }
  }
}
</script>

Currently, there is a race condition where the value of localStorage.mySpecialVariable is null when the inner template runs its create() method. Sometimes it's there, sometimes it's not unless I run the page twice.

How can I ensure that the outer main template code completes before anything continues?

2

There are 2 best solutions below

0
On BEST ANSWER

So after a ton of testing and research, I ended up updating the router.js file and running my code before each route is executed which did exactly what I need it to do.

router.sj

router.beforeEach((to, from, next) => {    
    doTheThing(to.query.Token, next);
});

let doTheThing = async (token, next) => {    
    await apiService.doTheThing()
    .then((response) => {
        //Do Stuff Here
        next();
    })
    .catch(() => {
        
    });
}

So what happens is that the function above will run and complete before any of the page specific code runs, which was the main goal and question I was asking. I hope someone else finds this helpful.

2
On

If the app depends on an API response, I would defer mounting the app until the response is received:

// main.js
ApiService.fetch()
  .then((response) => {
    localStorage.mySpecialVariable = response.data.foo;
  })
  .catch((error) => {
    console.error(error);
  })
  .then(() => {
    // ok to mount
    new Vue({/*...*/}).$mount();
  })