react-router icon indicating copy to clipboard operation
react-router copied to clipboard

Can't get transitionTo to work from within promise resolve

Open mwq27 opened this issue 11 years ago • 17 comments

Here's my code:

routes = (
        <Route handler={AppContainer}>
            <Route name="admin" path="/admin" handler={Admin}>
                <Route name='login' handler={AdminIndex}/>
                <Route name="dashboard" handler={AdminDashboard} />
            </Route>
        </Route>
);
Router.run(routes, Router.HistoryLocation, function (Handler) {
    React.render(<Handler/>, document.body);
});
var Admin = React.createClass({
    mixins: [Router.Navigation],

    render : function(){
        return(
            <div>
                <NavBar class="style-two"/>
                <RouteHandler />
            </div>
        );
    }
...
var AdminIndex = React.createClass({
    mixins : [ Router.Navigation ],

    getInitialState : function(){
        return _getAdminState.apply(this);
    },
    _loginUser : function(creds){
        var self = this;
        UserActions.adminLogin(creds).then(function(res){
            console.log('Succesful call', res);
            UserStore.setAdminLoginToken(res.body);
            self.transitionTo('/admin/dashboard');
        }, function (err){
            console.debug('big error son', err);
        });
    },
    _onChange : function() {
        if(UserStore.isAuthenticated()) {
            this.transitionTo('/admin/dashboard');
        }
        this.setState(_getAdminState.apply(this));
    },
    componentDidMount: function() {
        UserStore.addChangeListener(this._onChange);
    },
    componentWillUnmount: function() {
        UserStore.removeChangeListener(this._onChange);
    },

    render : function () {
        console.debug('isAdmin', this.state.isAdmin);
        return (
            <div className='container'>
                <div className='row'>
                    <h1>Admin Login</h1>
                    <LoginForm loginUser={this._loginUser}/>
                </div>
            </div>
        );
    }
});

There in the _loginUser() method in AdminIndex, I am calling transitionTo, and the warning I get thrown is

ReactMount: Root element has been removed from its original container. New container: null

And nothing will load for me on the /admin/dashboad page.

Does anyone see something that I'm missing?

UPDATE: I changed the router container from :

React.render(<Handler/>, document.body);

to

React.render(<Handler/>, document.getElementById('main');

and the transition is working, with no more react warning.

mwq27 avatar Dec 12 '14 23:12 mwq27

please let us know if you discover what the problem was :)

ryanflorence avatar Feb 01 '15 04:02 ryanflorence

I have the same problem now.

darkyen avatar Feb 07 '15 13:02 darkyen

Upon further inspection this is what I found out. screen shot 2015-02-07 at 7 18 43 pm

For some reason there are 2 routers at the same place :-/ or maybe the Promise is eating out the error.

darkyen avatar Feb 07 '15 13:02 darkyen


  getInitialState(){

    var query = this.getQuery();

    console.log('Get Initial State', this.getRoutes());
    if( query.access_token ){
      var at = query.access_token;
      app.http.setHeaders({
        'Authorization': 'MRAuth ' + at
      });
    }

    console.log("does this needs authes");
    var needsAuth = this.getRoutes().reduce(function(currentState, route){
      return currentState || app.restrictedRoutes.indexOf(route.name) !== -1;
    }, false);
    if( needsAuth && app.user.isLoggedIn() === false ){
      setTimeout(function(){
        self.transitionTo('/login/');
      }, 10);
    }

    return {};
  }

The above works but


  getInitialState(){

    var query = this.getQuery();

    console.log('Get Initial State', this.getRoutes());
    if( query.access_token ){
      var at = query.access_token;
      app.http.setHeaders({
        'Authorization': 'MRAuth ' + at
      });
    }

    console.log("does this needs authes");
    var needsAuth = this.getRoutes().reduce(function(currentState, route){
      return currentState || app.restrictedRoutes.indexOf(route.name) !== -1;
    }, false);
    if( needsAuth && app.user.isLoggedIn() === false ){
        self.transitionTo('/login/');
    }

    return {};
  }

But without the defer it doesn't.

darkyen avatar Feb 07 '15 14:02 darkyen

I'm having the same issue when deep linking into the app from an email link. It appears to be a race condition, but I haven't been able to drill down to the root cause.

tmcwilliam avatar Feb 17 '15 22:02 tmcwilliam

Can you make a minimal failing project?

gaearon avatar Feb 18 '15 00:02 gaearon

Unless you use async transition handlers or render async in your run callback, this.transitionTo(..) effectively translates to React.render(..). So starting a new transition within getInitialState or componentDidUpdate will start a new render before the ongoing one is finished.

You should use Handler.willTransitionTo and then redirect instead.

agundermann avatar Feb 18 '15 01:02 agundermann

moving transitionTo out of React life cycle methods fixed the problem. Is there a life cycle method that is safe to use transitionTo?

tmcwilliam avatar Feb 18 '15 03:02 tmcwilliam

@taurose This bit more than one person. Should we document this?

gaearon avatar Feb 18 '15 10:02 gaearon

I guess so. Perhaps we can also show a warning. I wonder why react doesn't.

agundermann avatar Feb 18 '15 18:02 agundermann

hi @taurose, I'm having the same issue.

I need to look at this.props to decide which route I should transition to, so willTransitionTo doesn't help here, since it's static.

Short of creating a global for this sole purpose (I think should work), do you guys have any other suggestion ?

jbrodriguez avatar Jun 18 '15 17:06 jbrodriguez

I've got the same problem. I want to conditionally redirect based on this.props.params, so willTransitionTo can't work. Using componentWillMount though triggers this error message.

robert-chiniquy avatar Aug 01 '15 06:08 robert-chiniquy

Having the same issue. Seems like calling transitionTo from the componentWillMount of my top level handler creates a new Router instance, I imagine because there's some condition somewhere checking if the handler had mounted yet.

My code is like:

routes.js
<Route name='root' path='foo' handler={Application}>
   <Route name='bar' path='bar'>
   </Route>
</Route>

application.js
...
componentWillMount() {
   if (this.state.dataSource.shouldGoToOnboarding) {
        router.transitionTo("bar");
   }
}
...

I tried changing componentWillMount to componentDidMount and that seemed to fix the issue, though it seems like a hack to get around the bug more than the proper solution.

eipark avatar Aug 18 '15 19:08 eipark

Hmm, this bit me too. Would love a way to abort mounting/rendering when calling transitionTo from inside componentWillMount

robyoder avatar Sep 01 '15 05:09 robyoder

I ended up with a hacky workaround. Perform the check in componentWillMount and setState with the result, then return null in render if the check failed (so as to not start rendering child components that depend on a successful check), then transitionTo in componentDidMount

robyoder avatar Sep 01 '15 07:09 robyoder

I too had this problem but doing this:

statics: {
    willTransitionTo: function (transition, params, query) {
        if (someCheck()) {
            transition.redirect('newroute');
        }
    }
},

Seems to work just fine. I couldn't use @robyoder 's solution because I was rendering components "outside" the router as well.

veddermatic avatar Sep 13 '15 00:09 veddermatic

I was having the same issue and moving transitionTo to componentDidMount did the trick. I'm glad I found this thread! I'm using 0.13.1. Does anyone know if this is any different with 1.0?

rafaelbiten avatar Sep 30 '15 14:09 rafaelbiten