0

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?

tony19
  • 125,647
  • 18
  • 229
  • 307
Camille Sévigny
  • 5,104
  • 4
  • 38
  • 61
  • you can add an `if` statement on the child component to be loaded after the data in the parent are finished. – Evan Feb 20 '21 at 02:51
  • @Evan I don't think this will work unless the child is always polling the variable to see if and when it's ready. This doesn't seem to be the way to go in this scenario. The child needs to run always and only after the parent has completed it's task. – Camille Sévigny Feb 20 '21 at 16:01

2 Answers2

0

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();
  })
tony19
  • 125,647
  • 18
  • 229
  • 307
  • This is interesting. I am very new to Vue, does the Local storage still work and is available in this context? I will give this a try. – Camille Sévigny Feb 20 '21 at 14:52
  • Yes. [`localStorage` is a standard browser API](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) and does not require Vue. – tony19 Feb 20 '21 at 18:41
0

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.

Camille Sévigny
  • 5,104
  • 4
  • 38
  • 61