4

I have a react application, where I'm using a handler the set the state, for some input forms

<div class="form-group has-danger">


 <label class="form-control-label" for="inputDanger1">Username</label>
  <input type="text" name="username" value={this.state.username} onChange={this.onChange} className={this.state.isUsernameCorrect ? "form-control is-valid" :"form-control is-invalid"} id="inputInvalid" />
  {this.state.isUsernameCorrect ? <div class="valid-feedback">Username is acceptable!</div> :
  <div class="invalid-feedback">Please enter a valid username</div> }
</div>

<div class="form-group has-danger">
  <label class="form-control-label" for="inputDanger1">Password</label>
  <input type="password" name="password" value={this.state.password} onChange={this.onChange} className={this.state.isUsernameCorrect ? "form-control is-valid" :"form-control is-invalid"} id="inputInvalid" />
  {this.state.isPasswordCorrect ? <div class="valid-feedback">password is acceptable!</div> :
  <div class="invalid-feedback">Please enter a valid password</div> }
</div>

with a respective handler

onChange = (e) =>{
    const name = e.target.name;
    const value = e.target.value;
    this.setState(
      {[name] : value
      },

  () => this.usernameValidator(this.state.username),
  () => this.passwordValidator(this.state.password)


  );
 }

I want to pass two separate functions, which validates the username and password with a regex pattern. Furthermore, it controls the state, of the display messages, if the password/username is correct or not.

However I want to execute both functions (and more maybe, for adding more form data), but setSatet only accepts one callback?

1 Answer 1

9

setState callback accepts only one function, but inside you can pass as many functions as you like.

this.setState({ [name] : value },
   () => {
      this.usernameValidator(this.state.username);
      this.passwordValidator(this.state.password);
   }
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.