Reputation: 3
I tried accessing localStorage inside asyncData but the result is "localStorage is not defined"
asyncData(){
if(localStorage.getItem("myCat")){
alert(localStorage.getItem("myCat"));
return;
}
}
Upvotes: 0
Views: 3767
Reputation: 5837
localStorage
is not defined because asyncData()
is resolved on the server during SSR. The localStorage
variable is only accessible in the client browser.
See documentation: https://nuxtjs.org/docs/features/data-fetching/. You can use localStorage in the mounted()
hook.
Upvotes: 2
Reputation: 101
In addition to Jakub Záruba's answer, if you need to access localStorage
in asyncData
nonetheless, you can modify your if
-statement like this:
if (process.client && localStorage.getItem("myCat")) {
alert(localStorage.getItem("myCat"))
return
}
so you will run this piece of code only on the client-side.
Upvotes: 2