Search code examples
javascriptmeteormeteor-react

Error handling on login


I'm currently trying to do an application using Meteor along with React, and I'm stuck doing the login form. Indeed, I want to use ReactComponent.state to save form's errors and display them

Meteor.loginWithPassword(email, password, err => {
  if (err) {
    this.setState({error: true, errorMessage: "User not found or password incorrect!"});
    return;
  } else {
  }
});

Unfortunately this does not seem to work (it raises a warning):

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Signin component.

You might not need it, but here is the render function in which I use ReactComponent.state to display error

render() {
return <form onSubmit={this.handleSubmit}>
  {this.state.error
    ? <p style={{
        color: 'red'
      }}>{this.state.errorMessage}</p>
    : ""}
  <label>Email</label>
  <br/>
  <input type="email" value={this.state.email} onChange={this.handleChange('email')} required/>
  <br/>
  <label>Password</label>
  <br/>
  <input type="password" value={this.state.password} onChange={this.handleChange('password')} required/>
  <br/><br/>
  <button type="submit">Sign in</button>
</form>
}

The Meteor.loginWithPassword is inside the handleSubmit function. I suppose that ReactComponent.state can't be updated in a callback, but I have no clue why and how to make it work.

Of course, I did not forget the initialState of the component:

getInitialState: function() {
  return {email: '', password: '', error: false, errorMessage: ''};
},

Thank you


Solution

  • We found the issue, in fact, we followed this article to handle roles and permissions in our app, the problem was that in the template, we were using loggingIn: Meteor.loggingIn(), which is also used by Meteor.loginWith* function hence our layout was dynamically re-rendered when calling this function in the form submission, to avoid this issue, we changed the loggingIn state with

    loggingIn: FlowRouter.current().route.group.name !== "public" && Meteor.loggingIn()
    

    To avoid dynamic reloading of the template when calling submitting the form.