Chenxi Yuan
Chenxi Yuan

Reputation: 164

firebase.auth.currentUser returns null until enter something in the form

I am using firebase and react router v4 to write my web app.

The application has two pages: LoginPage and ProfilePage.

When the user is logged in, I want to redirect the user to ProfilePage if they try to access the LoginPage. When the user is not logged in, I want to redirect the user to LoginPage if they try to access the ProfilePage.

In the LoginPage render method:

render() {
        console.log("login status: " + !!firebase.auth().currentUser);

        if (firebase.auth().currentUser) {
            console.log("login");
            return <Redirect to='/profile' push/>
        }
        return (
            <div className="container">
                <form onSubmit={this.handleSubmit}>

                    <h1>Login</h1>
                    <label>
                        Username
                        <input type="text" value={this.state.email} onChange={(event) => this.setState({email: event.target.value})} />
                    </label>
                    <label>
                        Password
                        <input type="password" value={this.state.password} onChange={(event) => this.setState({password: event.target.value})} />
                    </label>
                    <button type="submit">Login</button>
                </form>
            </div>
        );
    }

In the ProfilePage render method:

render() {
        console.log("login status: " + !!firebase.auth().currentUser);

        if (!firebase.auth().currentUser) {
            console.log("profile");
            return <Redirect to={'/login'} push/>
        }
        return (
            <div><h1>Profile</h1></div>
        );
    }

The problem: In the LoginPage, after I log in and refresh the page, the currentUser is null. Until I enter something in the username text field, the currentUser will be an Object, and it will redirect me to the ProfilePage.

Expect: If the user is logged in, when the user accesses the LoginPage, it should redirect the user to the ProfilePage instantly.

Upvotes: 1

Views: 1888

Answers (1)

Chenxi Yuan
Chenxi Yuan

Reputation: 164

The problem seems to be: The firebase.auth().currentUser is not updated immediately when I refresh the page.

I added firebase.auth().onAuthStateChanged() method in the index.js. When the auth status changed, I call the forceUpdate() method to force the component to re-render.

componentWillMount() {
        firebase.auth().onAuthStateChanged(
            (user) => {
                this.forceUpdate();
                console.log("onAuthStateChanged: " + !!user);
            }
        );
    }

Upvotes: 4

Related Questions