React meteor login error causing state error


#1

I know this has been asked before, but I’m not understanding what’s causing the problem. In this case when a user submits the login request handleSubmit is called and the page runs Meteor.loginWithPassword. The problem occours when there is a server error, ie. the users password is incorrect. this.setState({ loginError: true }) returns a console error:

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 LoginPage component.

I realise it’s something to do with the component unmounting when the form is submitted but I don’t understand how I suppose to fix it.

export default class LoginPage extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      email: '',
      errors: {},
      password: '',
      loginError: false
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  handleSubmit(event) {
    event.preventDefault();

    Meteor.loginWithPassword(email, password, (error, result) => {
      if (error) {
        this.setState({ loginError: true });
      } else {
        console.log("success");
      }
    });
  }

  render() {
    return (
      <div>
        <form noValidate>

          {this.state.loginError
            ?
              <div className="alert alert-danger text-center" role="alert">
                Incorrect username or password.
              </div>
            : null
          }

          <SingleInput
            name={'email'}
            inputType={'email'}
            controlFunc={this.handleInputChange}
            content={this.state.email}
            placeholder={'Email'}
            bsSize={null}
            error={this.state.errors && this.state.errors.email}
          />

          <SingleInput
            name={'password'}
            inputType={'password'}
            controlFunc={this.handleInputChange}
            content={this.state.password}
            placeholder={'Password'}
            bsSize={null}
            error={this.state.errors && this.state.errors.password}
          />
          
          <button className="btn btn-success btn-block" onClick={this.handleSubmit}>Login</button>
          
        </form>
      </div>
    );
  }
}