Skip to content Skip to sidebar Skip to footer

Multiple SetState() Calls In A React Method: How To Make It Work "synchronously"

So I had a problem in my React application, I ran into a specific case where I needed to have multiple setState() calls in one method, and then have code run AFTER the states were

Solution 1:

React documentation encourages the use of componentDidUpdate instead of the callback parameter of setState.

Yet, if you think the code seems a bit messy, try out local consts and make a single call to setState:

handleSubmit() {
  const {user, pass, passConfirm} = this.refs;
  const userError = user.getValue() ? null : "This field is required";
  const passError = pass.getValue() ? null : "This field is required";
  const passConfirmError = !passError && pass.getValue() === passConfirm.getValue()
    ? null
    : "Passwords do not match";

  this.setState({userError, passError, passConfirmError});

  if(!userError && !emptyPassError && !passConfirmError)
    alert('worked');
}

Finally, documentation also recommends the use of callback refs over strings refs:

Using the ref callback just to set a property on the class is a common pattern for accessing DOM elements. If you are currently using this.refs.myRefName to access refs, we recommend using this pattern instead.


Post a Comment for "Multiple SetState() Calls In A React Method: How To Make It Work "synchronously""