Smokey Dawson
Smokey Dawson

Reputation: 9230

Add functions to nuxt.config.js

Basically I have an app and on generate, I generate all pages, a sitemap and a RSS feed currently though I have to make the same axios call 3 times

like so

nuxt.config.js

generate: {
    routes: function() {
        return axios.get(data)
            .then(res => {
            ... 
            })
    }
},
sitemap: {
    routes: function() {
        return axios.get(data)
            .then(res => {
            ... 
            })
    }
},
feed: {
   etc...
}

now Is there a way I can call the data once and feed it to each of these module methods?? I tried putting some functions at the top of the nuxt.config.js but I was getting errors on generate

Upvotes: 1

Views: 1243

Answers (1)

Phil
Phil

Reputation: 164766

You could try saving the promise into a variable for re-use, eg

const routesPromise = axios.get(data).then(({ data }) => data)

// snip

generate: {
  routes () {
    return routesPromise.then(data => {
      // ...
    })
},
sitemap: {
  routes () {
    return routesPromise.then(data => {
      // ...
    })
  }
},
// etc

Adding .then() calls to the promise won't modify the original resolved value so you can keep using it as many times as you want while only making a single HTTP request.

Upvotes: 2

Related Questions