I've got a home route '/' and whenever a user goes to that route I want to send him either to his page if he is authenticated or send him to '/login' route if he isn't authenticated. In order to send a user to his page I make a request to the server, fetch his id and redirect him to the route based on the id I get from the server. However I'm a bit confused as to how to implement that logic in my Home component correctly. What would be the best way to render redirect component based on the result of the ajax request?
class Home extends React.Component {
async componentDidMount() {
const response = await Api.getUserId();
const id = response.data._id;
}
render() {
if(this.props.userStatus.authenticated) {
return <Redirect to={{
pathname: `/${id}`,
state: { from: this.props.location }
}}/>
}
return <Redirect to={{
pathname: '/login',
state: { from: this.props.location }
}}/>
}
}
export default connectComponent(['userStatus'], Home);
You can do this: Create a new component called PrivateRoute:
import React from 'react'
import { Redirect, withRouter, Route } from 'react-router-dom'
import { isLogin } from '../actions/actions_rents'
import { connect } from 'react-redux'
const PrivateRoute = ({ component: Component, ...rest }) => {
return(
<Route {...rest} render={props => (
isAuthenticated ? (
<Component />
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
)
}
And then in you App.js or where you have your routes, you call PrivateRoute and pass as props the component Home in this case:
<Switch>
<Route path="/login" component={Login}/>
<PrivateRoute path="/" component={IndexRents} />
</Switch>
Also, I recommend you see this example: https://reacttraining.com/react-router/web/example/auth-workflow
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