Skip to content Skip to sidebar Skip to footer

Submit Button Takes 2 Clicks To Call Function In React

When i'm clicking submit button it requires to clicks to properly fire off the function. I didn't have problem before implementing if statements. Does it have something with fact t

Solution 1:

You also shouldn't need to have two setState calls directly after each other. Make them in one setState instead like so:

this.setState({ validation: false, errorMessage: 'Please enter correct email adress', )}


Solution 2:

I think you are using a stale value of validation in the statement if(validation). Can you please try something like:

onSubmit = (e) => {

const { firstName, lastName, email, eventDate} = this.state

if (firstName, lastName, eventDate, email) {
  this.setState({validation: true})
  if (new RegExp(/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,15}/g).test(email)) {
    this.setState({validation: true})
  } else {
    this.setState({validation: false})
    this.setState({errorMessage: 'Please enter correct email adress'})
  }
} else {
  this.setState({validation: false});
  this.setState({errorMessage: 'Please fill in all fields properly'})
} 

const {validation} = this.state // read correct validation.. not something that was previously set

if (validation) {

  const newEvent = {
    firstName: this.state.firstName,
    lastName: this.state.lastName,
    email: this.state.email,
    eventDate: this.state.eventDate
  }

  this.props.addEvent(newEvent);

  this.setState({
    firstName: '',
    lastName: '',
    email: '',
    eventDate: '',
    validation: false,
    errorMessage: ''
  });
}

e.preventDefault();
}

Solution 3:

Fixed this issue, they key to success was moving my if(validation) statement body to callback function of setState.

Here is working code:

  onSubmit = (e) => {
const { firstName, lastName, email, eventDate, validation} = this.state

if (firstName, lastName, eventDate, email) {
  this.setState({validation: true})
  if (new RegExp(/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,15}/g).test(email)) {
    this.setState({validation: true}, () => {
      const newEvent = {
        firstName: firstName,
        lastName: lastName,
        email: email,
        eventDate: eventDate
      }
      this.props.addEvent(newEvent);

      this.setState({
        firstName: '',
        lastName: '',
        email: '',
        eventDate: '',
        validation: false,
        errorMessage: ''
      })
    })
  } else {
    this.setState({validation: false, errorMessage: 'Please enter correct email adress'})
  }
} else {
  this.setState({validation: false, errorMessage: 'Please fill in all fields properly'})
}
e.preventDefault();
}

Post a Comment for "Submit Button Takes 2 Clicks To Call Function In React"