3

I'm new in this amazing site, I'm just having a problem in my react app.

this is the index.js I'm using react-router-dom in this page I just need to show this.state.show for who is in a home page, So in the login.js request I've created 'loginToken' with this code sessionStorage.setItem('loginToken', 'Value')

and now I'm making a verification for sessionStorage.getItem('loginToken') in index.js

Everything works fine but my problem is when I'm in a home page this text 'Welcome Back' doesn't appears automatically I need to refresh the home page to see it. I don't know why this happening.

Is it because I'm using componentWillMount?

I've tried to use componentDidMount I got same problem

import React, {Component} from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

import Login from './users/login';
import home from './news/index';

class App extends Component {
    constructor(props){
        super(props);
        this.state = {
            show: false
        }
    }
    componentWillMount(){
        if(sessionStorage.getItem('loginToken')){
            this.setState({show: true});
        }else{
            this.setState({show: false});
        }
    }
    render() {
        return (
            <div>
                {this.state.show?
                <div>welcome back</div>:null
                }
            <Router>
                    <Switch>
                        <Route path="/login" component={Login} />
                        <Route path="/home" component={home} />
                    </Switch>
            </Router>
            </div>
        )
    }
}
export default App;

Thank you so much for helping me.

Laura delgado
  • 362
  • 2
  • 8
  • 21

1 Answers1

1

This issue is componentWillMount only fires once when the app first is run since it is the most top level component in the tree.

You should look to pass a function as a prop into the Login component and call it in the login component to trigger a state change back in the parent component. You could follow an approach to doing so in this article.

The easiest approach would be to just move that welcome back text into a dashboard or home route this way it mounts and unmounts as you are expecting and you can use your current approach in that component.

Eric Hasselbring
  • 1,374
  • 1
  • 10
  • 18