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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With