1

I've been trying to figure this out for hours but everything I try fails. I'm trying login a user and on success get route the user to the correct url based on the user's role. In the example below, I login successfully, and the user is successfully identified however when I try to redirect or push.history it doesn't let me. There are no errors, it just stays on the login url.

I'm using: React router 4, Meteorjs

handleSubmit(event) {
  event.preventDefault();

  Meteor.loginWithPassword(email, password, (error, result) => {
    if (error) {
      this.setState({ loginError: 'Incorrect username or password.' });
    } else {
      if (!!Roles.userIsInRole(Meteor.userId(), 'isAdmin')) {
        <Redirect to="/admin/dashboard" push />
      }
    }
  });
}
bp123
  • 3,217
  • 8
  • 35
  • 74
  • I am unformilliar with the `!!` syntax. But what I read is if error, redirect user to admin panel if he or she is admin. Not anything about an incorrect login. Add a {} for an else statement for the first if statement to handle an incorrect login, or an if statement for the first true as I'm not sure what `loginWithPassword` does. – Xorifelse Dec 05 '17 at 22:35
  • 1
    There's no problem with the if statement. It fires correctly. The problem I have is that it doesn't `Redirect`. – bp123 Dec 05 '17 at 22:39
  • Is a full blow html/xml statement gonna help meteor? Read [this](https://stackoverflow.com/questions/21315896/redirect-after-login-using-meteor-and-iron-router). As I don't see how a redirect statement can be html. – Xorifelse Dec 05 '17 at 22:46
  • Thanks, but this isn't the issue. User role can't be verified if the user isn't logged in. The problem I'm having is with `Redirect`. I'm not having much luck figuring out how to do a simple redirect with react router 4. – bp123 Dec 05 '17 at 22:57
  • @Xorifelse it's React's JSX not html – azium Dec 05 '17 at 23:31
  • @Xorifelse sorry I'm not understanding. Are you telling me to post this another way? – bp123 Dec 05 '17 at 23:32
  • 1
    `` can only be used in `render()`. so either set some state and do `{this.state.redirect && }` or use `history.push`. `history` is passed from `` – azium Dec 05 '17 at 23:32
  • 1
    I can write out a full answer but try this ^. there are many stackoverflow posts about navigating with react router – azium Dec 05 '17 at 23:41

1 Answers1

1

A react component is something that is rendered, it's not just a function that you can call from anywhere.

Use history.push('/admin/dashboard")

If the router is being passed into your component as a prop you might also find yourself doing

this.props.history.push('/admin/dashboard")
Michel Floyd
  • 18,793
  • 4
  • 24
  • 39