Search code examples
http-redirectreactjsecmascript-6react-routerflux

ReactRouter doesn't redirect correctly after flux notification


I'm a newbie in react and flux. As a matter of facts I stumbled into the following problem when using ReactRouter (2.4)

I'm using hashHistory and I need to redirect to the "/" page when I'm in "/login" page after a successful login attempt.

Router

ReactDOM.render(
<Router history={hashHistory}>
    <Route path="/" component={App}>
        <IndexRoute component={ErasmusPage} onEnter={authCheck}></IndexRoute>
        <Route path="login"component={withRouter(LoginPage)}></Route>
    </Route>
</Router>, app);

Login Page

constructor() {
    super();
    this.notifyLogin = this.notifyLogin.bind(this);
    this.state = {
        email: "",
        password: ""
    };
}

componentWillMount() {
    authStore.on("login", this.notifyLogin);
}

componentWillUnmount() {
    authStore.removeListener("login", this.notifyLogin);
}

notifyLogin() {
    this.props.router.push('/');
}

...

handleSubmit(e) {
    e.preventDefault();

    let data = {
        email: this.state.email,
        password: this.state.password
    };
    AuthActions.authenticate(data);
}
...

The flow is:

  1. after one submits, authActions and Store elaborate the datas (ajax call involved).
  2. If the login attempt is all right, AuthStore emits a "login" signal...
  3. ... so i can execute notifyLogin().

The problem is: this.props.router.push('/') doesn't redirect properly, it changes the URL but not the page (it looks like the state refresh doesn't get triggered).

Weird thing is, if I put this.props.router.push('/') in the handleSubmit function the redirect works perfectly.

Any idea of what's going on?


Solution

  • This has worked well for me so far:

    • Wrap your app in an component that contains login/auth state.
    • on render, if not logged in, render the login page component, otherwise, render the app component

    render() {
      const { isAuthorized, authError} = this.props;
      
      if (isAuthorized) {
        return (<Layout />);
      }
      
      return (<Login authError={authError}/>);
    }