In this lesson, you'll learn how to set up a submit handler that posts your form data to a serverless function.
Jason Lengstorf: [0:00] To get our form to submit to our serverless function, let's open up the source folder and then we're going to go into components and form.tsx. We're going to make a couple changes here. The first thing is, we want to bring in React, because we're going to pull out types from the React object.
[0:15] Next, we want to add one more useState. That's going to let us hold on to the response from our serverless function. We'll call this Response, and set Response as useState. We'll just leave that one undefined.
[0:27] Next, we need to have a function that will actually process that form submission. We're going to go with async function handleSubmit. That is going to receive an event.
[0:39] Now, because this is TypeScript, we need to give that event a type. The type that we want is React.SyntheticEvent. That's going to receive an HTML form element. That's how we type a form submission in React.
[0:59] Inside, we're going to prevent the default. We don't want it to actually submit to itself.
[1:04] If name = empty and favorite color = empty, we're just going to short-circuit. We don't want to actually submit, so no empty form submissions. Then we will get a response by awaiting a fetch call to our serverless functions, so .netlify functions submit.
[1:29] We're going to use the post method here. Method = post, and the body is going to be JSON stringify name and favorite color. Once we get that back, we will get that response and turn it into JSON. Once we've got that response back, we're going to set it in state.
[1:56] We're also going to reset our form. We'll set name to zero and set favorite color back to an empty string. We've reset our form. This should empty it once we've submitted. We've stored the response from our serverless function here.
[2:10] Then we just need to display that response somewhere. Let's get out here and we'll just stringify our response. We'll set that to null too, so that it's a little bit easier to read. Then we just need to add the on submit handler to actually call handleSubmit.
[2:30] Once we've saved this, we can come out here and let's add it and give it a try. My name is Jason. My favorite color is yellow. I hit Submit and there we go. We have now submitted to our serverless function. Name is Jason. Favorite color is yellow. Message, "My name is Jason. My favorite color is yellow."
[2:46] That's exactly what we expected, and it's reset the form for us. If we try it again, set it to Tom, and favorite color is pink, it works as expected.
[2:58] We've now got a serverless function written in TypeScript receiving submissions from a React form written in TypeScript, all being built with Vite and run locally by nullified dev.