Problems Dropdown Selection Issue: Users can only click on the first year in the…
- User
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 ( <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 : 'اختر السنة الدراسية'}
code - Assistant