| Level Navigation: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19⚡ | 20 |
Goal: Create the handleAddMeal function to process form submissions.
User Story: As a developer, I want to create a form handler so that I can process the form data when users submit it.
Add the handleAddMeal function to your component to handle form submissions.
async function handleAddMeal(event) that:
event.preventDefault() to prevent page refreshevent.target.elementsnewMeal object with the form dataparseInt(serves)Need help with the form handler? Check out these snippets:
async function handleAddMeal(event){
event.preventDefault()
console.log("handle add meal submitted")
const mealName = event.target.elements.mealName.value
const guestName = event.target.elements.guestName.value
const serves = event.target.elements.serves.value
const kindOfDish = event.target.elements.kindOfDish.value
const newMeal = {
meal_name: mealName,
guest_name: guestName,
serves: parseInt(serves),
kind_of_dish: kindOfDish
}
console.log(newMeal)
// We'll add the insert logic in the next step
}
Understanding form events:
event.preventDefault(): Stops the browser’s default form submission behavior (page refresh)event.target: References the form element that triggered the eventevent.target.elements: Collection of all form input elements with name attributesExploring the event object:
To better understand how events work, try adding this to your form handler:
function handleAddMeal(event) {
console.log(event); // Examine the entire event object
console.log(event.target); // Look at the form element
console.log(event.target.elements); // See all form inputs
event.preventDefault();
// ... rest of your code
}
What you’ll see in the console:
event: A large object with many properties (type, target, preventDefault, etc.)event.target: The <form> element that was submittedevent.target.elements: A collection of all inputs with name attributesForm data extraction pattern:
const mealName = event.target.elements.mealName.value
const guestName = event.target.elements.guestName.value
elements.mealName: Gets the input with name="mealName".value: Gets the current value from that inputuseState for each field (controlled inputs), but this is simplerData type conversion:
serves: parseInt(serves)
parseInt(): Converts string to integerparseInt("abc") returns NaN - in production, you’d validate thisObject creation pattern:
const newMeal = {
meal_name: mealName,
guest_name: guestName,
serves: parseInt(serves),
kind_of_dish: kindOfDish
}
meal_name) vs. form field names (mealName)📺 Learn More: