How to async global Mixin data in Nuxt JS?

879 views Asked by At

First, let me share my workflow. In my nuxt app, I am trying to track if the user is from desktop or mobile by getting the window width of the user. To do that,

Firstly, I am using js's window object in my default.vue to update the height and width variable in my store. Here is the code

//default.vue

 created() {
      if (process.browser) {
        window.addEventListener('resize', this.handleResize);
        this.handleResize(window.innerHeight, window.innerWidth);
      }
    },
}
 methods: {
      handleResize() {

        this.$store.commit('setwindowheightwidth', {
          height: window.innerHeight,
          width: window.innerWidth
        })
      },
}

After that, I have created a plugin to keep my mixins. And in the mixin, I am populating my isMobile variable by getting the width variable value from store.

import Vue from "vue"

export default ({store}) => {
 // Make sure to pick a unique name for the flag
// so it won't conflict with any other mixin.
if (!Vue.__my_mixin__) {
  Vue.__my_mixin__ = true
  Vue.mixin({ 
    data: function() {
        return {
          isMobile: store.getters.windowWidth<768,
        }
      },
     
   }) // Set up your mixin then
}
}

Now I am getting this data in my every component and pages, just as I was intending. But when I am loading the page first time, or refreshing the page, the value is returning true! Even when the actual value is false. But if I go to other page by navigating or come back to the initial one (without refreshing), I am getting the actual value. So it seems for some reason the value is not updating on initial loading of any of my pages. Usually I fix this kind of issue by getting the data using async-await, but not sure where to use that here. How can I update the mixin data from it's inital state on my page load?

1

There are 1 answers

0
Davoud Ebrahimi On

I think, if you use computed property, instead of data value, your problem will be solved. Also, you can install @nuxt-device module and use it to detect current device in each page. If these approaches don't solved your problem, just store the values in the state and persist them by cookies.

import Vue from "vue"

export default ({store}) => {
 // Make sure to pick a unique name for the flag
// so it won't conflict with any other mixin.
if (!Vue.__my_mixin__) {
  Vue.__my_mixin__ = true
  Vue.mixin({ 
    computed:{
       isMobile(){
          return store.getters.windowWidth<768;
       }
     }
   }) // Set up your mixin then
}
}