user9389851
user9389851

Reputation:

dynamic vue router - beforeEnter - infinite loop when using next()

I am trying to create a SPA which shows dealer in every state of austria. For example if a user visits example.com/vienna it shows every dealer in vienna. But if a users visits example.com/paris, he will still get directed to the dynamic route /paris but of course there will be nothing shown.

So my approach was to check if the state which the user wants to search for is available in the list of state and therefore directing it to the available state or redirect him to a 404 page.

If the state is available it works, but if I'll try to go to a non existing state I am stuck in a loop from next('/404')

export default new Router({
  routes: [{
      path: '/',
      name: 'Home',
      component: Home
    },{
      path: '/:region',
      component: RegionQuery,
      beforeEnter: (to, from, next) => {

        let isRegion = false;
        let allRegions = storeConfig.state.states;
        let toRegion = to.params.region;

        for(var i in allRegions){
          if(allRegions[i].route === toRegion){
            isRegion = true;
          }
        }

        if (isRegion) {
          next();
        } else {
          next('/404');
        }
      }
    },
    {
      path: '/404',
      name: '404',
      component: NotFound
    },
    {
      path: '*',
      redirect: '/404'
    },
  ],
})

What am I doing wrong or is there a better approach to my problem?

Upvotes: 0

Views: 1279

Answers (1)

ittus
ittus

Reputation: 22403

/404 is matched to /:region

You need to change your path order

export default new Router({
  routes: [{
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/404',
      name: '404',
      component: NotFound
    },{
      path: '/:region',
      component: RegionQuery,
      beforeEnter: (to, from, next) => {

        let isRegion = false;
        let allRegions = storeConfig.state.states;
        let toRegion = to.params.region;

        for(var i in allRegions){
          if(allRegions[i].route === toRegion){
            isRegion = true;
          }
        }

        if (isRegion) {
          next();
        } else {
          next('/404');
        }
      }
    },
    {
      path: '*',
      redirect: '/404'
    },
  ]

Upvotes: 1

Related Questions