anbhd
anbhd

Reputation: 125

Keep user logged in on refresh using local storage with React

I'm trying to use local storage so that on refresh, the user is still logged in rather than being signed out every time. I've managed to save data to local storage using this code (I'm using Firebase so I'll leave a lot of it out):

 saveToLocal(){
    const local = this.state.loggedIn;
    localStorage.setItem("loggedIn", JSON.stringify(local));
}

loginUser(e){
    e.preventDefault();      
    this.setState({
        loggedIn: "true"
    }, 
    this.saveToLocal);

How do I now go about accessing the data in local storage and have it set the state right away so that the user remains logged in on refresh? Here's my state:

constructor(){
    super();

    this.state = {
        loggedIn: ""
    }

Thank you!

Upvotes: 0

Views: 3960

Answers (1)

Mario Nikolaus
Mario Nikolaus

Reputation: 2406

Your could do something like this. In root component track your user logged in/out status. If you already have localStorage item then you just read on componentDidMount value of localStorage and set state depending on that value.

localStorage.getItem('loggedIn')

But maybe the better solution would be to use cookies, depending on how much you want to keep your user logged in. With cookies you can add time dimension to whole logic.

Upvotes: 2

Related Questions