mardi 20 novembre 2018

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 that i have 2 if statements inside and after each click it checks only 1 if statement?

  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})
  } 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'})
} 

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();
}

Aucun commentaire:

Enregistrer un commentaire