React: How to use localStorage in componentWillMount

Created on 10 May 2017  路  5Comments  路  Source: facebook/react

I am learning react js and i want to check if authentication token is set or not in localStorage before the component renders.
Currently i am trying to do it inside componentWillMount method, but it gives me warning that localStorage is not defined.
So how can i access localStorage?

Most helpful comment

Hey @BhumiSukhadiya!

We try to use this issue tracker for bug reports and feature requests only. If you have a usage or support question, we recommend checking out one of the great community-driven platforms like Reactiflux, discuss.reactjs.org, or StackOverflow.

If you're doing server-side rendering then accessing localStorage in componentWillMount might throw an error on the server. It's usually safest the DOM in componentDidMount

All 5 comments

@BhumiSukhadiya are you accessing it from window.localStorage?

@Alexintosh @BhumiSukhadiya It's right. You must use window.localStorage

Hey @BhumiSukhadiya!

We try to use this issue tracker for bug reports and feature requests only. If you have a usage or support question, we recommend checking out one of the great community-driven platforms like Reactiflux, discuss.reactjs.org, or StackOverflow.

If you're doing server-side rendering then accessing localStorage in componentWillMount might throw an error on the server. It's usually safest the DOM in componentDidMount

@aweary I used local Storage to get session Id and key based on these only site will load. how to use local storage in componentDidMount? while running Server-side-rendering got an error.

Was this page helpful?
0 / 5 - 0 ratings