handleAddFood doesnt add a single row with one button click:


import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import "./CreateDietPlanWithId.css";

function CreateDietPlanWithId() {
  const { userId } = useParams();
  const [userName, setUserName] = useState("");
  const [mealTimes, setMealTimes] = useState([
    { name: "صبحانه", foods: [] },
    { name: "نیم چاشت اول", foods: [] },
    { name: "نیم چاشت دوم", foods: [] },
    { name: "نهار", foods: [] },
    { name: "عصرانه اول", foods: [] },
    { name: "عصرانه دوم", foods: [] },
    { name: "شام", foods: [] },
    { name: "وعده قبل از خواب", foods: [] },
  ]);
  const [foodCategories, setFoodCategories] = useState({});
  const [selectedFoods, setSelectedFoods] = useState([]);

  const fetchUserData = async () => {
    try {
      const response = await fetch(`http://localhost:5000/api/users/${userId}`);
      if (response.ok) {
        const userData = await response.json();
        setUserName(userData.name); // Set the user's name
      } else {
        console.error("Failed to fetch user data:", response.statusText);
      }
    } catch (error) {
      console.error("Error fetching user data:", error);
    }
  };

  const fetchFoodOptions = async () => {
    try {
      const response = await fetch("http://localhost:5000/api/food");
      if (response.ok) {
        const data = await response.json();
        setFoodCategories(data.food);
      } else {
        console.error("Failed to fetch food options:", response.statusText);
      }
    } catch (error) {
      console.error("Error fetching food options:", error);
    }
  };

  useEffect(() => {
    fetchUserData();
    fetchFoodOptions();
  }, [fetchUserData]);

  const handleCategoryChange = (mealIndex, foodIndex, event) => {
    const { value } = event.target;
    const updatedSelectedFoods = [...selectedFoods];
    updatedSelectedFoods[mealIndex * mealTimes[0].foods.length + foodIndex] = {
      ...updatedSelectedFoods[mealIndex * mealTimes[0].foods.length + foodIndex],
      category: value,
    };
    setSelectedFoods(updatedSelectedFoods);
  };

  const handleSubcategoryChange = (mealIndex, foodIndex, event) => {
    const { value } = event.target;
    const updatedSelectedFoods = [...selectedFoods];
    updatedSelectedFoods[mealIndex * mealTimes[0].foods.length + foodIndex] = {
      ...updatedSelectedFoods[mealIndex * mealTimes[0].foods.length + foodIndex],
      subcategory: value,
    };
    setSelectedFoods(updatedSelectedFoods);
  };

  const handleAddFood = (mealIndex) => {
    setMealTimes((prevMealTimes) => {
      const updatedMealTimes = [...prevMealTimes];
      
      // Check if a row has already been added for this meal index
      if (!updatedMealTimes[mealIndex].rowAdded) {
        updatedMealTimes[mealIndex].foods.push({ category: "", subcategory: "" });
  
        // Set the flag to indicate that a row has been added for this meal index
        updatedMealTimes[mealIndex].rowAdded = true;
      }
  
      return updatedMealTimes;
    });
  };
  
  

  const handleSubmit = () => {
    // Placeholder for handling form submission
    console.log("Form submitted!");
  };

  return (
    <div>
      <h1>برنامه غذایی روزانه {userName}</h1>
      <br />
      <div>
        <p>شناسه کاربر: {userId}</p>
      </div>
  
      {mealTimes.map((meal, mealIndex) => (
        <div key={mealIndex}>
          <h2>{meal.name}</h2>
          <div>
            {meal.foods.map((food, foodIndex) => (
              <div key={foodIndex}>
                <select
                  value={selectedFoods[mealIndex * meal.foods.length + foodIndex]?.category || ""}
                  onChange={(e) => handleCategoryChange(mealIndex, foodIndex, e)}
                >
                  <option value="">انتخاب دسته بندی غذا</option>
                  {Object.keys(foodCategories).map((category, i) => (
                    <option key={i} value={category}>
                      {category}
                    </option>
                  ))}
                </select>
                <select
                  value={selectedFoods[mealIndex * meal.foods.length + foodIndex]?.subcategory || ""}
                  onChange={(e) => handleSubcategoryChange(mealIndex, foodIndex, e)}
                >
                  <option value="">انتخاب زیر دسته بندی غذا</option>
                  {selectedFoods[mealIndex * meal.foods.length + foodIndex]?.category &&
                    foodCategories[
                      selectedFoods[mealIndex * meal.foods.length + foodIndex]?.category
                    ]?.map((subcategory, i) => (
                      <option key={i} value={subcategory}>
                        {subcategory}
                      </option>
                    ))}
                </select>
              </div>
            ))}
            <button onClick={() => handleAddFood(mealIndex)}>افزودن غذا</button>
          </div>
        </div>
      ))}
  
      <div className="button-container">
        <button className="buttonx" onClick={handleSubmit}>
          ثبت برنامه
        </button>
      </div>
    </div>
  ); 
  
}

export default CreateDietPlanWithId;