I'm still developing my understanding of async functions and ReactJS, but in the context of a form submission, why might I start my async function with e.preventDefault()?
I saw this code as an example of how to post form data in React (see article link), but they didn't explain why their code begins with e.preventDefault()
. I'm not sure if this has to do with the async feature, how React renders things, or any other concept I'm not grasping.
I thought e.preventDefault()
would prevent the form from submitting, so I'm reading this code (which is tied to the "onSubmit" attribute of a form element), as "anytime I submit a form, the submission will be automatically cancelled".
Any help would be much appreciated, thank you.
let handleSubmit = async (e) => {
e.preventDefault();
try {
let res = await fetch("https://httpbin.org/post", {
method: "POST",
body: JSON.stringify({
name: name,
email: email,
mobileNumber: mobileNumber,
}),
});
let resJson = await res.json();
if (res.status === 200) {
setName("");
setEmail("");
setMessage("User created successfully");
} else {
setMessage("Some error occured");
}
} catch (err) {
console.log(err);
}
};
event.preventDefault()
stops the default behavior of an action. Often times we call this in a vanilla HTML form "Submit" operation.
If you're curious, the default behavior of a submit on a form can be read about here: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#method
To answer your question, this is stopping all of the default behavior that would normally occur when submitting a form. The code following is what you actually want to happen when submitting.