3

I'm using react router v4 and trying to implement a protected api view. E.g., if a user goes to /add/ url while not logged in, they would be redirected to /login/, then upon successful login taken to /add/.

I was able to implement it using the idea from this post. However, I run into issues whenever the initial http request that loads the app is from a protected url.

E.g. when I enter in the browser '/add/' and hit enter, I run into async issues where my app doesn't have time to make an ajax request to the server to check for login, and as a result the router ends up routing to the /login/ because ajax auth request hasn't completed.

Can someone recommend login workflow should be handled generally, taking into account the fact that a user may start their session on a protected url like '/add/' and not on the home '/'?

Nad
  • 436
  • 4
  • 16

1 Answers1

3

Found a simple, standard React pattern solution. Just don't render <Route> components unless the log in ajax check has completed.

So when the app loads for the first time, initialize a state checkingLogIn to true and don't render any <Route> component unless it becomes false. When the ajax function checking for log in completes, call setState to set checkingLogIn to false. This will cause the <Route> to render and redirect correctly.

Edited with sample code:

componentDidMount(){
// call the ajax function that checks if the user is logged in and update state when it returns; using fetch API here
 fetch(your_url, your_credentials)
   .then(
     that.setState({checkingLogIn: false, isLoggedIn: true})
        )
   .catch(...)
}
// render method of the React component
render(){
    if(this.state.checkingLogIn){
    return (<div>Loading...</div>)
    }
    else {
      return (
       <Route path={some_path} render={props => <SomeComponent {...props} />}></Route>
      )
    }

}
Nad
  • 436
  • 4
  • 16