0

I am attempting to hit an endpoint https://api.com/signup.ashx which has issues with CORS. So I was asked to make the API call without axios nor fetch or anything like that.

So I did this:

const handleSubmit = async (event) => {
    let error = false
    let message = ""

    Object.keys(value).forEach((element) => {
      let val = value[element]
      if (!val) {
        error = true
        message = "Please complete all required fields."
      }

      if (element == "email" && val && !validateEmail(val)) {
        error = true
        message = "Please enter valid email address"
      }
    })

    if (error) {
      alert(message)
    } else {
      try {
        console.log("succesful response")
      } catch (error) {
        console.log("error", error)
      }
    }

    event.preventDefault()
  }

return (
      <form
        id="signup"
        name="signup"
        method="post"
        autocomplete="off"
        onsubmit={handleSubmit}
        action="https://api.com/signup.ashx"
      >...</form>
)

We do not care if the page reloads. The problem is that it reloads and takes the user to an error route:

locahost:8000/?result=error which makes me think that the call to the endpoint isn't working.

Regarding the CORS situation, it is not on me. I was just asked to do it as I mentioned.

So do you have any idea what the problem with my code is?

Reacting
  • 3,765
  • 4
  • 24
  • 56

1 Answers1

0

Navigation in react is controlled by routers. You have to use router instead of form's action. Refer React Router v4 Redirecting on form submit

Also the event.preventDefault should be the first statement in the submit function.

soumya sunny
  • 206
  • 1
  • 7