Terje Nygård
Terje Nygård

Reputation: 1257

React handleSubmit (with axios.post) with e.preventDefault still refreshes

First or all.. i'm very, very new to React and either though i have googled through a lot of posts regarding exactly this.. i have still yet not found out why my page refreshes.. anyone care to take a look ?

I have also tried e.stopPropagation() and e.nativeEvent.stopImmediatePropagation() without success..

Let me know if you need additional information:

Registration.JS

import React, {
  Component
} from 'react';
//import logo from './logo.svg';
import '../App.css';

const isValidPostalCode = value => /^\d{4}$/.test(value)
const isValidEmail = value => /^([a-zA-Z0-9_.+-])+@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(value)
const isValidPhone = value => /^\[0-9]{8}$/.test(value)

class Registration extends Component {
  constructor(props) {
    super(props)
    this.state = {
      formData: {
        firstName: "",
        lastName: "",
        email: "",
        phone: "",
        postalCode: "",
      },
      formErrors: {
        firstName: null,
        lastName: null,
        email: null,
        phone: null,
        postalCode: null,
      }
    }
  }

  onFirstNameChange(e) {
    console.log("FN = ", e.target.value)
    this.setState({
      formData: {
        ...this.state.formData,
        firstName: e.target.value
      },
    })
  }
  onLastNameChange(e) {
    this.setState({
      formData: {
        ...this.state.formData,
        lastName: e.target.value
      },
    })
  }
  onEmailChange(e) {
    const {
      value
    } = e.target

    this.setState({
      formData: {
        ...this.state.formData,
        email: value,
      },
      formErrors: {
        ...this.state.formErrors,
        email: isValidEmail(value) ? null : "Legg inn gyldig epost",
      }
    })
  }
  onPhoneChange(e) {
    const {
      value
    } = e.target

    this.setState({
      formData: {
        ...this.state.formData,
        phone: e.target.value
      },
      formErrors: {
        ...this.state.formErrors,
        phone: isValidPhone(value) ? null : "Telefonnummeret må være 8 tall",
      }
    })
  }
  onPostalCodeChange(e) {
    const {
      value
    } = e.target

    this.setState({
      formData: {
        ...this.state.formData,
        postalCode: e.target.value
      },
      formErrors: {
        ...this.state.formErrors,
        postalCode: isValidPostalCode(value) ? null : "Postnummer må være 4 tall",
      }
    })
  }
  render() {
    console.log("logging props in registration", this.props)
    return ( <
      form onSubmit = {
        (e) => {
          this.props.handleSubmit(e, this.state.formData.firstName, this.state.formData.lastName, this.state.formData.email, this.state.formData.phone, this.state.formData.postalCode)
        }
      } >
      <
      div className = "page-content" >
      <
      h3 > Registrering < /h3>

      <
      span > {
        this.props.trumfData.registrationintro
      } <
      /span>

      <
      span className = "registration-block" >
      <
      div className = "registration-block-line" >
      <
      input type = "text"
      placeholder = "Fornavn"
      onChange = {
        (e) => this.onFirstNameChange(e)
      }
      value = {
        this.props.trumfData.firstname ? this.props.trumfData.firstname : this.state.formData.firstName
      }
      /> <
      input type = "text"
      placeholder = "Etternavn"
      onChange = {
        (e) => this.onLastNameChange(e)
      }
      value = {
        this.state.formData.lastName
      }
      /> <
      /div> <
      div className = "registration-block-line" >
      <
      input type = "text"
      placeholder = "Epost"
      onChange = {
        (e) => this.onEmailChange(e)
      }
      value = {
        this.state.formData.email
      }
      /> {
        this.state.formErrors.email
      } <
      /div> <
      div className = "registration-block-line" >
      <
      input type = "text"
      placeholder = "Telefon"
      onChange = {
        (e) => this.onPhoneChange(e)
      }
      value = {
        this.state.formData.phone
      }
      /> {
        this.state.formErrors.phone
      } <
      input type = "text"
      placeholder = "Postnr"
      onChange = {
        (e) => this.onPostalCodeChange(e)
      }
      value = {
        this.state.formData.postalCode
      }
      /> <
      /div> <
      /span> {
        " "
      } {
        this.props.trumfData.isauthenticatd && < input type = "checkbox" > Kryss av... < /input>
      } <
      input type = "submit"
      value = "Registrer din stemme" / >

      <
      /div> <
      /form>
    );
  }
}

export default Registration;

APP.JS

handleSubmit(e, firstName, lastName, email, phone, postalCode) {
  alert('Submitted: ' + firstName + ", " + lastName);
  e.preventDefault();
  e.stopPropagation();
  e.nativeEvent.stopImmediatePropagation();
  this.setState({
    step: 3,
    ...this.state.userVote,
    FirstName: firstName,
    LastName: lastName,
    Email: email,
    MobileNumber: phone,
    ZipCode: postalCode
  })
  axios.post('http://localhost:54467/api/poll/vote', this.state.userVote)
    .then(response => {
      console.log("VI HAR SENDT INN !!!:", response.data)
      // this.setState({ trumfdata: response.data })
    })
    .catch(err => console.log("Error", err))
}

Upvotes: 1

Views: 3167

Answers (1)

Michael Sorensen
Michael Sorensen

Reputation: 2124

Solution: Add e.preventDefault() to the form's onSubmit property

form onSubmit = {
    (e) => {
      e.preventDefault();
      this.props.handleSubmit(e, this.state.formData.firstName, this.state.formData.lastName, this.state.formData.email, this.state.formData.phone, this.state.formData.postalCode)
    }
  } >

But Why though? preventDefault() simply needs to be the first thing that you do otherwise you run the risk of of whatever event you are trying to prevent running before you have a chance to stop it. I made a codepen to illustrate what I mean: https://codepen.io/anon/pen/odfgavb

[Edit] The previous answer I provided was wrong. It's possible that the true issue lies within passing the function down as a prop. I can't be sure. If anyone does know why please post the answer here.

Upvotes: 1

Related Questions