Home > Enterprise >  React Typescript: get sessionStorage after reload of page
React Typescript: get sessionStorage after reload of page

Time:01-16

After the User Sign In, a authentication token is saved in the sessionStorage and the Page gets Reloaded. Now after the reload I want to read that data and store it in a state but the render dont change from <Login /> to <Layout>...

export default class Home extends React.Component<any, State> {
    constructor(props: any) {
        super(props);
        this.state = {
            auth: true,
        }

        this._auth();
    }

   public render() {
        return (
            <>
                {this.state.auth ?
                    <Login /> :
                    <Layout>
                    ...
                    </Layout>
           </>
        )
   };

   private _auth(): void {
        if (sessionStorage.getItem("accessGranted") !== "")
            this.setState({ auth: true });
        else
            this.setState({ auth: false });
   }

CodePudding user response:

Do not call setState() in constructor(). Instead, if a component needs to use a local state, assign the initial state to this.state directly in the constructor.

componentDidMount() invokes immediately after a component mounts. You can call setState() immediately in componentDidMount() and triggers an extra rendering, but this happens before the browser updates the screen, calling render() twice.

read more here

Either you can return the value of your sessionStorage from _auth method and use that value to create the state inside the constructor, OR you can simply call this._auth inside componentDidMount() which is still okay but mainly used for async computations, side effects etc.

  •  Tags:  
  • Related