Update status when switching React

Asked

Viewed 107 times

0

I’m taking the name of the person through the localstorage and passing to the state to show on screen the problem is that when I change page, Going from login page to home it does not show on screen directly already tried as componentDidMount, only when I give an F5 it appears to me on screen, I would have another alternate besides the componentDidMount and componentDidUpdate?

class Home extends Component {
    constructor(props) {
        super(props);
    
        this.state = { 
          firstname: '',
        };   
    }

    componentDidMount() {
        const name = localStorage.getItem('@front-end/firstname');
        this.setState({ firstname: name });
    }

    out = () => {
        localStorage.removeItem('@front-end/firstname');
        this.setState({ firstname: ''});
    }

    render() {
        document.title = "Home - VirtualBooks";

        return (
            <>
                <h1>Hello {this.state.firstname}</h1>
                <Link to="/login">Login</Link>
                <button onClick={this.out}>Sair</button>
            </>
        )
    }
}

  • 1

    Strange your question because at the same time has a method that changes the state to empty ... it is strange ...

  • I call this to delete the localstorage, and so empty the variable, the question is how I can show on screen when I enter the page

  • 1

    You do not need to empty the variable ... it seems that your doubt is another, and it is only working because you are pressing F5 logic and created the variable again ... there is something else in your doubts.

  • you tried to put the initial value of this state already with the value of localStorage? Another tip is also to use the Hooks, it is much more.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.