3

I'm having an issue with extendRoutes in nuxt.config.ts

When i build my nuxt and generate pages i want my router to know which comonent goes to which path based on an api call..

so in Nuxt.config.ts i do this:

 router: {
  extendRoutes(routes resolve){
    cms.getRoutes().then(x => { <-- this returns an array from api call with objects needed for path
       for(var i = 0; i < x.items.lenth; i++){
         routes.push({
            name: x.items[i].name,
            component: component: resolve(__dirname, `pages/index.vue`), <- this is just and ex. of comp.
            path: x.items[i].slug,
         });
       }
    })
  }
}

This creates an inifinite loop because but i dont await the response. But if I use async/await i get an nuxt error saying "routes.forEach is not a function".

Here is the async version:


async extendRoutes(routes: any, resolve: any) {

        await cms.GetSitemap().then((x: any) => {
            for(var i = 0; i < x.items.lenth; i++){
             routes.push({
               name: x.items[i].name,
               component: component: resolve(__dirname, `pages/index.vue`),
               path: x.items[i].slug,
             });
        });
    }

this gives this error as soon as i try to build:

nuxt error on async / await

3
  • could u show us ur async attempt Commented Jun 24, 2020 at 11:59
  • yes i will edit the question with async Commented Jun 24, 2020 at 12:07
  • @Ifaruki it is now editted Commented Jun 24, 2020 at 12:11

2 Answers 2

2

Well that's not the way how to use async / await. It should eliminate .then() chaining, but you still used it here. Try it like this:

router: {
  async extendRoutes(routes, resolve) {
    let x = await cms.getRoutes();
    for (var i = 0; i < x.items.length; i++) {
      routes.push({
        name: x.items[i].name,
        component: resolve(__dirname, `pages/index.vue`),
        path: x.items[i].slug
      });
    }
  }
};
Sign up to request clarification or add additional context in comments.

2 Comments

as explained can't i use async await ;) even though i use async withot anything inside extendRoutes it gives routes.foreach is not a function
you cant use forEach() with async, but you can use for(). @AndersBootsmannLarsen
0

I ended up using the nuxt router module ( https://github.com/nuxt-community/router-module ) where i could remove the nuxt router and create my own.

Here could i use api calls and with await / async and create the logic for the routing i wanted.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.