Skip to content
Advertisement

nuxt 2.14 generate does not update asyncData

I’m following closely to this feature (https://nuxtjs.org/blog/nuxt-static-improvements/#generate-time-cache-vs-full-webpack-build)

I may be getting this wrong, but I hope to clarify if I can use this feature correctly.

Basically, I want to skip the webpack build as highlighted in the article, and build my pages through nuxt generate. The thing is that my data source usually changes, but my site code does not, and I thought using the nuxt generate in Nuxt 2.14 would be helpful for my use case in skipping the webpack build.

However, on running the nuxt generate command which skips the webpack build and jump straights to the generating of pages, the pages generated seem to be updated (as expected), but the data inside asyncData does not seem to be getting updated/refreshed.

nuxt.config.js

generate: {
    crawler: false,
    async routes() {
      let finalArray = readFinalArrayFromSomeDatabase();

      await fs.writeJson('static/data/index.json', finalArray); // writing new array to static folder

      generateSomeNewRoutes(finalArray); // working correctly!!!
    }
}

some _slug.vue

async asyncData(params) {
    // this runs after previous code runs
    const testArray = require("../../../static/data/index.json"); // this is not updated!!!
}

The index.json written is updated, but the index.json read in asyncData is NOT. Is there some way to trigger the change in asyncData? Or Does that mean I have to always rebuild webpack when my data change and cant use this feature in nuxt 2.14?

Advertisement

Answer

Within your asyncData you are loading the JSON with require, which adds the JSON to the webpack build, so it’s not updated after that point.

Instead, you can use a payload to pass your data through to the asyncData. For example:

  generate: {
    crawler: false,
    async routes() {
      const finalArray = readFinalArrayFromSomeDatabase();

      return generateSomeNewRoutes(finalArray).map(route => ({ route, payload: finalArray }));
    }
}

Then in your component:

async asyncData({ payload }) {
  if (payload) {
    // you can now access the entire finalArray via payload
    // though note this will only work at generate time and during dev
    // you should have another solution to fetch/require data differently
  }
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement