Problems
Dropdown Selection Issue:
Users can only click on the first year in the dropdown; other years are unresponsive.
Undefined Properties Error:
An error occurs stating "cannot read properties of undefined (reading 'year')" when trying to display the selected academic year or after selecting a year.
Current Year Display:
The dropdown should always display the current year by default when the component is idle.
Additional Context
The component fetches a list of academic years from an API and allows users to select one.
The component needs to correctly handle state updates when a user selects a year, including marking it as the current year in the database.
Error handling should be in place to manage API call failures.
import React, { useState, useEffect } from 'react';
import { ChevronDown } from 'lucide-react';
import Logout from "../Logout.jsx";
import api from '../../api.jsx';

function AcademicYearDropdown() {
  const [years, setYears] = useState([]);
  const [isOpen, setIsOpen] = useState(false);
  const [academicYear, setAcademicYear] = useState(null); // Track the selected academic year
  const [error, setError] = useState(null); // Track errors

  const updateSchoolYear = async (yearId, updatedData) => {
    try {
      const res = await api.put(`/schoolyear/update/${yearId}/`, updatedData);
      if (res.status === 200) {
        setYears((prevYears) =>
          prevYears.map((year) => (year.id === yearId ? res.data.school_year : year))
        );
        setAcademicYear(res.data.school_year); // Update the selected year
      } else {
        throw new Error('Failed to update school year');
      }
    } catch (err) {
      console.error(err);
      setError(err.message || 'An error occurred');
      alert(error);
    }
  };

  const getYears = async () => {
    try {
      const res = await api.get("/schoolyears/");
      const fetchedYears = res.data;
      setYears(fetchedYears);
      const currentYear = fetchedYears.find(year => year.is_current); // Find the current year
      if (currentYear) {
        setAcademicYear(currentYear); // Set it as the default selected year
      }
    } catch (err) {
      console.error(err);
      setError(err.message || 'Failed to fetch school years');
      alert(error);
    }
  };

  useEffect(() => {
    getYears();
  }, []);

  const handleYearSelect = (year) => {
    const updatedData = { ...year, is_current: true }; // Create updated data
    updateSchoolYear(year.id, updatedData);
    setIsOpen(false);
  };

  return (
    <div className="dropdown relative inline-block text-left">
      <button
        onClick={() => setIsOpen(prev => !prev)}
        className="inline-flex justify-center w-full rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-sm font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-100 focus:ring-indigo-500"
      >
        السنة الدراسية: {academicYear ? academicYear.year : 'اختر السنة الدراسية'}
        <ChevronDown className="-mr-1 ml-2 h-5 w-5" />
      </button>

      {isOpen && (
        <div className="origin-top-right absolute right-0 mt-2 w-56 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5">
          <div className="py-1" role="menu" aria-orientation="vertical" aria-labelledby="options-menu">
            {years.map((year) => (
              <button
                key={year.id} // Ensure unique key based on the year ID
                onClick={() => handleYearSelect(year)}
                className="block w-full text-right px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 hover:text-gray-900"
                role="menuitem"
              >
                {year.year} {/* Ensure the property is defined */}
              </button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

function Header() {
  return (
    <div className="font-custom p-3 flex justify-between items-center bg-white shadow-sm">
      <h1 className="text-xl font-semibold text-gray-800">لوحة التحكم</h1>
      <div className="flex items-center space-x-4">
        <AcademicYearDropdown />
        <Logout />
      </div>
    </div>
  );
}

export default Header;
fix it