codex-lv3-may-2025

Level Navigation: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19⚡ 20

Level 10: Add Event Handler

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.


What You’ll Do

Add the handleAddMeal function to your component to handle form submissions.

Instructions

💡 Code Hints

Need help with the form handler? Check out these snippets:

Show Me: form handler
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
}

🔍 Diving Deeper

Understanding form events:

Exploring 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:

Form data extraction pattern:

const mealName = event.target.elements.mealName.value
const guestName = event.target.elements.guestName.value

Data type conversion:

serves: parseInt(serves)

Object creation pattern:

const newMeal = {
    meal_name: mealName,
    guest_name: guestName,
    serves: parseInt(serves),
    kind_of_dish: kindOfDish
}

📺 Learn More:

✅ Check

  1. Fill out the form with test data
  2. Submit the form
  3. Check the browser console - you should see “handle add meal submitted”
  4. You should see the newMeal object logged to console
  5. No page refresh occurs when submitting

📚 Vocabulary