Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing multiple functions as callback in setState

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?

like image 277
Dedi Avatar asked Jan 27 '23 00:01

Dedi


1 Answers

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);
   }
);
like image 77
kind user Avatar answered Jan 31 '23 23:01

kind user