Skip to content
Advertisement

In React and Next.js constructor, I am getting “Reference Error: localstorage is not defined”

I make a system jsonwebtoken in React and use Next.js. I find a problem when I run the code in the browser, that is, “localStorage is not defined”. How can I fix it?

This is my code in file AuthStudentContext.js:

JavaScript

And it shows error “localStorage is not defined”.

Advertisement

Answer

In the constructor, as well as componentWillMount lifecycle hooks, the server is still rendering the component. On the other hand, localStorage exists as part of the browser’s window global, and thus you can only use it when the component is rendered. Therefore you can only access localStorage in the componentDidMount lifecycle hook. Instead of calling localStorage in the constructor, you can define an empty state, and update the state in componentDidMount when you can start to call localStorage.

JavaScript
Advertisement