Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Route Firebase Auth Redirect after login

I am trying to redirect the user to UserProfile after login. I can login the user successfully but once logged in I cannot figure out why it doesn't redirect me to the UserProfile page.

Not sure what I am doing wrong. Can anybody have a look at this?

App.js

// ...
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';

class App extends Component {
  this.state = {
    isLoggedIn: null,
  };

  componentDidMount() {
    firebase.auth().onAuthStateChanged(user => {
      if (user) { this.setState({ isLoggedIn: true })} 
      else { this.setState({ isLoggedIn: false })}
    })
  }

  render() {
    return (
      <BrowserRouter>
        <Switch>
          <Route path='/' component={Landing} exact />
          <Route path='/login' component={Login} />
          <Route path='/user-profile' render={() => (
            this.state.isLoggedIn ? <UserProfile /> : <Redirect to='/login' />
          )} />
        </Switch>
      </BrowserRouter>
    );
  } 
}

export default App;

Login.js

// ...
import { withRouter } from 'react-router-dom'

class Login extends Component {
    this.state = {
        // ...
    };

    _handleSubmit = (e) => {
        e.preventDefault();
        firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password)
            .then(() => {
                // ...
                this.props.history.push('/recipe-form')
            }).catch((error) => {
                // ... 
            });
    }

    render() {
        return (
            <form onSubmit={(e) => this._handleSubmit(e)}>
                <Input //...Email />
                <Input //...Password />
                <Button text='Login' type='submit' />
            </form>
        );
    }
}

export default withRouter(Login);
like image 802
200gSoft Avatar asked Oct 16 '25 04:10

200gSoft


1 Answers

The checker you are putting on

<Route path='/user-profile' render={() => ( this.state.isLoggedIn ? <UserProfile /> : <Redirect to='/login' /> )}/>

here says that if user currently on user-profile path and he is not logged in, he should suppose to be re directed, but it is says nothing on user that currently in login path.

You can add same (but opposite) logic to Route login decleration -

<Route path='/login' render={() => ( !this.state.isLoggedIn ? <Login /> : <Redirect to='/user-profile' /> )}/>

or add Redirect at Login component itself after successful login attempt

like image 134
Hagai Harari Avatar answered Oct 17 '25 17:10

Hagai Harari