crimsonpython24
crimsonpython24

Reputation: 2383

Updating Props in React onSubmit

I have this Ant Design form and currently, I am stuck on outputting the error message: in the code block attached below, handleSubmit isn't responsive. I want to see the error message "Username and Password do not match" as soon as I submitted a wrong input but the message only shows after one of the field changes (I have multiple ones but I only put up this to keep things crisp).

For your information, "updating props" was logged as soon as I submitted the wrong data, but the error message only changes after an additional change was made to another field.

class NormalLoginForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {username: '', usernameProps: {},};
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event => event.preventDefault();
    postData('/account/login', this.state)
    .then(data => {
      if (data.success) {window.location = '/';}
      else {
        this.usernameProps = {
          hasFeedback: true, validateStatus: "error",
          help: "Username and Password do not match"
        }
        console.log('updating props');                // Here is the log
      }
    });
  }

  render () {
    return (
      <Form
        style={{ width: "100%" }} onFinish={this.handleSubmit}
        noValidate 
      >
        <Form.Item name="username" {...this.usernameProps}
         onChange={this.handleUsernameChange}>
          <Input placeholder="Username"/>
        </Form.Item>
        <Form.Item>
          <Button type="submit" htmlType="submit" style={{ width: "100%" }}>
            Log in
          </Button>
        </Form.Item>
      </Form>
    )
  }
};

ReactDOM.render(<NormalLoginForm />, document.getElementById("root")); 

Can anyone please tell me where did I do wrong? Many thanks in advance.

Upvotes: 0

Views: 683

Answers (1)

Rohan Agarwal
Rohan Agarwal

Reputation: 2609

When updating states use the setState method and avoid updating the state directly as you are doing here.

 this.usernameProps = {
      hasFeedback: true, validateStatus: "error",
      help: "Username and Password do not match"
 }

Do this:

const userNameState = {...this.state.usernameProps, hasFeedback: true, validateStatus: "error",
                      help: "Username and Password do not match"};
this.setState({usernameProps: userNameState});

You can use this state in the form as this.state.usernameProps

Upvotes: 1

Related Questions