reactjs - Rendering redirect component based on ajax request -


i've got home route '/' , whenever user goes route want send him either page if authenticated or send him '/login' route if isn't authenticated. in order send user page make request server, fetch id , redirect him route based on id server. i'm bit confused how implement logic in home component correctly. best way render redirect component based on result of 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 this: create new component called privateroute:

import react 'react' import { redirect, withrouter, route } 'react-router-dom' import { islogin } '../actions/actions_rents' import { connect } 'react-redux'  const privateroute = ({ component: component, ...rest }) => {     return(         <route {...rest} render={props => (         isauthenticated ? (         <component />         ) : (         <redirect to={{           pathname: '/login',           state: { from: props.location }         }}/>       )     )}/>   ) } 

and in app.js or have routes, call privateroute , pass props component home in case:

<switch>   <route path="/login" component={login}/>   <privateroute path="/" component={indexrents} /> </switch> 

also, recommend see example: https://reacttraining.com/react-router/web/example/auth-workflow


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -