How to Handle a Submit for a Form
1 min readAug 30, 2021
Hiya!
If you’re working with a form in javascript or react, and want to understand the “POST” fetch with the onSubmit, keep reading!
This weekend I was creating authentication for the user and a user could also create a post.
I have a couple fetches to juggle, but here is the code for the submit!
const postSubmit = (e, title, description, image, category) => { //prevent the page from refreshing
e.preventDefault();
const token = localStorage.token; fetch("*backend link here*", { method: "POST", headers: { "Content-Type": "application/json", },
//stringify your inputs into JSON format body: JSON.stringify({ userId: userID, title: title, description: description, image: image, category: category, }), })
//after the fetch is done, receive a json response object .then((response) => response.json())
//set the response data to state inside of react .then((data) => setData(data)) .catch((err) => {console.log("error posting" + err);});};
This piece is for the submit function that will take the event from the form.
With the form itself, you can submit the inputs from the user events two ways:
With a button
<buttontype="submit"onClick={(e) => {handleLogin(e, user, password);}}className="border border-solid rounded-full py-1 px-3 transform translate-y-3 text-white transition-shadow duration-300 ease-in-out uppercase hover:shadow-lg"style={{ backgroundColor: "#ff9f1c", borderColor: "#ff9f1c" }}>Log in</button>
If it’s with a button you have to make sure that the type is equal to submit (type=”submit”).
<form onSubmit={(e) => handleSubmit(e, user, password)}> //code here
</form>
Happy hacking!
-Crystal