Vue - check localStorage before initial route (for token)

Viewed 482

I have a Vue app which does a little localStorage and server check on app load, to determine where to initially route the user.

This is in the App's main entry component, in the created() hook

My problem is that the default / route's Component visibly loads first, then the server call and everything happens which causes the user the route to their correct location

How can I delay the rendering of the initial component until my app's main component created() method completes, and then purposely navigates the user to the correct route?

2 Answers

I had this problem before and I firmly believe that you must have the initial files for your routes and your router configuration.

In the configuration, you could handle the permission and router before each route and with next() . In the router file, you can set your params and check them in the index.js file(router configuration)

you could also use your localStorage data in Router.beforeeach

enter image description here

enter image description here

EDIT: I just saw you used the created method... like mentioned below use beforeRouteEnter instead with the next() parameter it provides

First of all I wouldn't recommend using a delay but instead a variable that keeps track if the API call is done or not. You can achieve this using the mounted method:

data() {
  return {
    loaded: false,
  }
}
async mounted() {
  await yourAPICALL()
  if (checkIfTokenIsOkay) {
    return this.loaded = true;
  }
  // do something here when token is false
}

Now in your html only show it when loaded it true:

<div v-if="loaded">
  // html
</div>

An better approuch is using the beforeRouteEnter method which allows you to not even load the page instead of not showing it: https://router.vuejs.org/guide/advanced/navigation-guards.html

Related