I am working on a Nuxt application where I need to display different components based on the window width and send a request to create a session with the device width as one of the header parameters. Here is my approach:
In my store code:
//index.js
export const state = () => ({
device_width: null,
session_data : {},
})
export const mutations = {
set_device_width(state, payload) {
return state.device_width = payload;
},
set_session_data(state, payload){
return state.session_data = payload
}
}
export const actions = {
//server init action to initialize the app with some necessary data
async nuxtServerInit({ commit }) {
if (process.browser) {
commit('set_device_width', window.innerWidth);
}
var device_type = "";
if (this.state.device_width < 768) {
device_type = "mobile";
} else if (this.state.device_width > 768) {
device_type = "desktop";
}
var sessionData= await axios(...//api request with 'device_type' in header//....)
commit('set_session_data', sessionData)
}
Then, in my templates, I use a computed method to retrieve the value.
computed:{
isMobile(){
return this.$store.state.device_width<768
}
}
When the screen size is below 768, everything works fine. However, when in desktop mode with full-screen, there's a brief moment where isMobile is true before becoming false and the desktop component loads. This results in the session data always being created with "device_type: mobile" initially. Additionally, due to the initial mobile UI display, the SEO elements of the desktop UI do not function properly. How can I address this issue? I aim to determine the screen size and store it prior to app initialization. I believed using the serverInit action would achieve this.