[Vuejs]-Is it possible for Nuxt middleware to wait for asyncData requests to resolve?

2πŸ‘

βœ…

I figured this out in a more elegant solution than having to implement a store.dispatch function on each individual asyncData function.

So what I did was use a custom loading component: https://nuxtjs.org/api/configuration-loading/#using-a-custom-loading-component

However, instead of showing a progress bar or any sort of loading animation, I just used this component to set a loading state in my vuex store. Note – it forces you to have a template, but I just permanently disabled it.

<template>
  <div v-if="false"></div>
</template>

<script>
  export default {
    methods: {
      start() {
        this.$store.dispatch('updateLoadingStatus', true);
      },
      finish() {
        this.$store.dispatch('updateLoadingStatus', false);
      }
    }
  };
</script> 

Then in my middleware, I set up an interval watcher to check when loading has stopped. When stopped, I stop the interval and close the mobile menu.

export default function({ store }) {

  if (store.state.page.mobileNav) {
    if (store.state.page.loading) {

      var watcher = setInterval(() => {
        if (!store.state.page.loading) {
          store.dispatch('updateMobileNav', false);
          clearInterval(watcher);
        }
      }, 100);

    } else {
      store.dispatch('updateMobileNav', false);
    }
  }
}

This doesn’t specifically have to be for a mobile menu open/close. It can be used for anything in middleware that needs to wait for asyncData to resolve. Hope this can help anyone in the future!

πŸ‘€DJDJ

3πŸ‘

I think that the best option would be to leave the menu open, and then when the new page finishes loading (probably on the mounted hook) send an event or action to close the menu.

πŸ‘€Eder DΓ­az

Leave a comment