I'm trying to get a value from localStorage to determine the value of a variable in store. I remember trying something similar with vuejs about a year ago and it seemed to work. I also have no issues with this on Reactjs. But for some reason i keep getting this error when doing the same in Nuxt


this is my user.js file
export const state = () => ({
isLoggedIn: !!localStorage.getItem('userDetails')
})
export const mutations = {
login(state) {
state.isLoggedIn = true;
},
logout(state) {
window.localStorage.clear()
state.isLoggedIn = false;
}
}
am i approaching this problem wrong? or is this not supposed to work? Any help is appreciated.
When you use SSR you don't have access to the browser storage.
To do a workaround, you can dispatch an action on the mounted component hook.
mounted() {
if(!process.client) return;
const savedData = localStorage.getItem("userDetails");
if(savedData){
this.$store.commit('myMutation',savedData)
}
}
Try it like this:
isLoggedIn: process.server ? '' : !!localStorage.getItem('userDetails')
The problem is that you try to access the localstorage while nuxt is on the server side. you need to check with process.server if you are on the server side or not. It returns either true or false.
I didnt tested it but with this ternary operator it should work.
Here: https://nuxtjs.org/faq/window-document-undefined/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With