persisting memory in React

Here is my code, I pass the auth state and token through props to other components: The problem is that when I refresh the page, it redirects me to the homepage.

Here is my code:

class App extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            account: {
                email: "",
                password: ""
            },
           
            token: "",
            auth: false
        };

    }
    
    
    confirm = async (email) => {
            let result;
            let stateAccount;
            let authToken;
            let myCookie;
            let storedCookie;

            try {
                result = await axios.post(`http://localhost:5000/abc/dosomething`, {email},{withCredentials: true});

                stateAccount = this.state.account
                stateAccount.email = email;
                this.setState({stateAccount});


                console.log(result);

                if (this.state.account.email === result.data.Email && this.state.account.password === result.data.OTPCode) {
                    authToken = result.headers.accesstoken;
                    this.setState({token: authToken});

                    myCookie = this.addCookies();
                    myCookie = myCookie.split('=');
                    storedCookie = myCookie[1].trim();

                } else {
                    console.log(`Invalid Login!`);
                    
                }


                let history = this.props.history;



                if(this.state.token === storedCookie){
                    console.log("Successful Login!");
                    console.log(`found cookie: ${storedCookie}`);
                    this.setState({auth: true});
                    history.push({pathname: "/some-endpoint/abc", state: {stateAccount}});

                }else{
                    this.setState({errorMessage: "Invalid Login!"});
                }



            }catch(error){ //set this to Permission Denied in production
                console.log(`${error.data}`});
            }
        }
    
    notLoggedInhomePage = () =>{

        if(!this.state.auth) {
            return (
                <form onSubmit={this.handleSubmit}>
                        <label>Email Address</Form.Label>
                        <input type="text" value={this.state.account.email} onChange={this.handleChange} name="email"/>
                    
                        <label>Password</Form.Label>
                        <input type="password" value={this.state.account.password} onChange={this.handleChange} placeholder="Enter One Time Password" name="password"/>
                    

                    <button type="submit" onClick={() => this.someFunction(String(this.state.account.email))}>Do Something</button>
                    <button type="submit" onClick={() => this.someOtherFunction()}>Do something else</button>
                </form>
            );
        }else{
            return(<Redirect to="/logged-in-page/signed-in" />);
        }
}


      render(){

        return(
            <Router>
                {this.notLoggedInhomePage()}
                <Switch>
                    <Route path="/list" exact component={AComponent} auth={this.state.auth} account={this.state.account} token={this.state.token}  />
                </Switch>
            </Router>
        );
    }

I know that state is an temporary-memory, but what I am looking to do is, when I refresh the page, I want the user to stay on the same page that they were on before refreshing. However what happens is that they get redirected back to the home page (which is the login screen), because the this.state.auth will be equal to false as seen above in the notLoggedInhomePage.

What is the best solution to fix the above problem ?

Answer

You could make use of localStorage

  • Set your state to app_state storage when your token is changed.
  • Check if app_state exist on the mount or using a fresh state.

Something like this:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = localStorage.getItem("app_state") ?? {
      account: {
        email: "",
        password: ""
      },
      token: "",
      auth: false
    };
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.token !== prevState.token) { // Set a new state if token change
      localStorage.setItem("app_state", this.state);
    }
  }
...the rest of your component