Search code examples
vue.jsvuexnuxt.js

Nuxt loading progress bar loads multiple times


I'm using default nuxt loading bar, it works well on simple pages. But when I use multiple axios requests progress bar loads every time request is sent. I want progress bar to understand all those request as a single page load. I used Promise.all and it kind of worked. But my problem is that I am using asynchronous vuex dispatch methods.

So my code is something like this, with three different asynchronous dispatch and progress bar loads three times. How can I make it so, that it loaded only once. Thanks

async fetch({  store }) {
    await store.dispatch('LOAD_DATA_1')
    await store.dispatch('LOAD_DATA_2')
    await store.dispatch('LOAD_DATA_3')
}

Solution

  • It's loading three separate times because your requests are taking place sequentially, one after another, not all at once. To get around this, you can manually start/stop the loader.

    First, you'll want to prevent the nuxt axios plugin from triggering the loading bar. See here.

    this.$axios.$get('URL', { progress: false })
    

    Then, you can manually start and stop the loading bar programatically before/after the requests are completed.

    this.$nuxt.$loading.start()
    this.$nuxt.$loading.stop()
    

    Full example:

    async fetch({  store }) {
        this.$nuxt.$loading.start()
        await store.dispatch('LOAD_DATA_1')
        await store.dispatch('LOAD_DATA_2')
        await store.dispatch('LOAD_DATA_3')
        this.$nuxt.$loading.stop()
    }
    

    edit 1 (see comment):

    To use in asyncData/fetch you can use the following. I'm not sure you should be accessing the components like this, but I don't see another way to access the $loading module within the context...

    async fetch(ctx) {
        // access the loading component via the access context
        ctx.app.components.NuxtLoading.methods.start()
    
        // example, wait 3 seconds before disabling loader
        await new Promise(resolve => setTimeout(resolve, 3000))
    
        ctx.app.components.NuxtLoading.methods.finish()
    },