How to access async store data in vue-router for usage in beforeEnter hook?

santacruz picture santacruz · Mar 3, 2017 · Viewed 22.2k times · Source

How is it possible to access store data in beforeEnter which is retrieved asynchronously via the store action?

import store from './vuex/store';

store.dispatch('initApp'); // in here, async data will be fetched and assigned to the store's state

// following is an excerpt of the routes object:
{
  path: '/example',
  component: Example,
  beforeEnter: (to, from, next) =>
  {
    if (store.state.asyncData) {
      // the above state is not available here, since it
      // it is resolved asynchronously in the store action
    }
  }
}

This is especially important on the first page load or after a page reload, when the init data is being fetched and the router needs to wait for that data to either allow the user to access that page or not.

Is it possible for the router to "wait" for the data to be fetched? Or what's the best way to handle navigation guard in combination with async vuex store data?

(oh and pre-populating "asyncData" can't be the solution, since the beforeEnter hook needs to make its decision on real data from the database, not default data)

Answer

Saurabh picture Saurabh · Mar 3, 2017

You can do it by returning a promise from vuex action, as it is explained here and call the dispatch from within the beforeEnter itself.

Code should look like following:

import store from './vuex/store';


// following is an excerpt of the routes object:
{
  path: '/example',
  component: Example,
  beforeEnter: (to, from, next) =>
  {
    store.dispatch('initApp').then(response => {
        // the above state is not available here, since it
        // it is resolved asynchronously in the store action
    }, error => {
        // handle error here
    })         
  }
}