Skip to main content

MERN Stack Create

Let's add a Form to create new Holiday, which we'll make as a separate component

add NewForm.jsx into the components folder

NewForm.jsx

NewForm.jsx
function NewForm() {
return <div>New Form</div>;
}

export default NewForm;

Add a Form in the render

NewForm.jsx
<form onSubmit={handleSubmit}>
<label>
Holiday:
<input type="text" name="name" placeholder="add a holiday" />
</label>
<input type="submit" value="Add a Reason to Celebrate" />
</form>

App.jsx

App.jsx
import NewForm from "./components/NewForm";
// further down
return (
<div className="container">
<h1>Holidays! Celebrate!</h1>
<NewForm />
<table>...</table>
</div>
);

Let's build out our handleSubmit functions

Now let's build our functionality

To submit, we have to prevent the default behavior of the form.

We also have to send this data back up to our app component so it can be passed down to the list.

App.js II

App.jsx
const addHoliday = (holiday) => {
setHolidays([...holidays, holiday]);
};
// further down (in render)
<NewForm handleAddHoliday={addHoliday} />;

We then have to make a fetch request. When we are just making a get request, we just use one argument, a string, where we are making our request. However, for any other action, we have to add a second argument, an object.

We'll have to add a method, a body (the data from our form), and some headers adapting from Supplying request options.

THEN when we get a response we need to convert it to json. This is an extra step we didn't have to take when we used $.ajax. Fetch is ultra-lightweight so we have to write a bit more code. You could use jQuery, axios, ky or other libraries, but our app is simple so let's just use fetch.

THEN we want to take that json-ed response and add our new holiday to our list

NewForm.jsx
const handleSubmit = (event) => {
event.preventDefault();

const formData = new FormData(event.target);
const data = Object.fromEntries(formData);

const payload = {
...data,
celebrated: true,
description: "",
likes: 0,
};

async function createHoliday(payload) {
const response = await fetch("/api/holidays", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
});
const jsonData = await response.json();
addHoliday(jsonData);
}
createHoliday(payload);
};