Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make an async call in a beforeCreate hook of a Vue instance?

I am building a Vuejs app with authentication.

When the page is loaded and I initialise the app Vuejs instance, I am using beforeCreate hook to set up the user object. I load a JWT from localStorage and send it to the backend for verification.

The issue is that this is an async call, and the components of this app object (the navbar, the views etc.) are being initialised with the empty user data before the call returns the result of the verification.

What is the best practice to delay the initialisation of child components until a promise object resolves?

Here is what I have in my Vue app object:

beforeCreate: function(){
    // If token or name is not set, unset user client
    var userToken = localStorage.userToken;
    var userName = localStorage.userName;
    if (userToken == undefined || userName == undefined) {
      StoreInstance.commit('unsetUserClient');
      // I WANT TO RESOLVE HERE
      return;
    }

    // If token and name is set, verify token
    // This one makes an HTTP request
    StoreInstance.dispatch({type: 'verifyToken', token: userToken}).then((response) => {
      // I WANT TO RESOLVE HERE
    }, (fail) => {
      // I WANT TO RESOLVE HERE
    })
  }
like image 339
Gábor Pintér Avatar asked Oct 25 '16 15:10

Gábor Pintér


1 Answers

The current lifecycle callbacks are functions without any promises/async behaviour. Unfortunately, there does not appear to be a way to cause the app to "pause" while you load data. Instead, you might want to start the load in the beforeCreate function and set a flag, display a loading screen/skeleton with empty data, flip the flag when the data has loaded, and then render the appropriate component.

like image 179
mlaccetti Avatar answered Oct 07 '22 01:10

mlaccetti