Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Nuxt Generate dynamic routes from the store

I’m using nuxt.js and now need to generate my dynamic pages by running npm run generate. However my list items needed to make dynamic items are stored in the store, so I need to map over them somehow so the generate can make the routes for them

How can I access the store in my nuxt.config.js?

generate: {
  dir: 'wwwroot', //override the default generation dir to create everything straight in wwwroot
  routes() {
    let vdc = this.$store.vdcServers.map(server => `/virtual-data-centres/${server.slug}`);
    return Promise.all([vdc]).then(values => {
      return values.join().split(',');
    })
  }
}

Output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 ERROR  Could not resolve routes                                                                        
 FATAL  Cannot read properties of undefined (reading '$store')   

>Solution :

To my knowledge, you cannot access the store from that place. Maybe with some hooks? I doubt.
Meanwhile, if you have your elements available in your store you should be able to find them back by making a quick axios call or like I think.

This kind of approach is totally fine

import axios from 'axios'

export default {
  generate: {
    routes(callback) {
      axios
        .get('https://my-api/users')
        .then(res => {
          const routes = res.data.map(user => {
            return '/users/' + user.id
          })
          callback(null, routes)
        })
        .catch(callback)
    }
  }
}

It may be a bit of code duplication, meanwhile, it’s still the simplest way to go.
Otherwise, you could try to persist it to some localStorage or any similar solution, to have it both in Vuex and during your generation.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading