यहाँ मेरा कोड है। मुझे विद्यार्थी का डेटा बैक से, फ़िल्टर करके मिल रहा है। मैं चयन विकल्प के लिए डिफ़ॉल्ट मान सेट करने में सक्षम नहीं हूं और न ही setAssignedStudent
काम कर रहा है, कंसोल में, मुझे undefined
मिल रहा है। कृपया मुझे बताएं कि इसे कैसे ठीक किया जाए।
//here is sample of students array
// let students- [ {name: "abc", email:"abc.com", mentor:"" },
// {name: "abc", email:"abc.com", mentor:"cda" }, {name: "abc", email:"abc.com", //mentor:"" }]
useEffect(() => {
const getStudents = async () => {
try {
const res = await fetch("http://localhost:3001/students");
const data = await res.json();
//console.log(data);
//filtering students based on who doesn;t have mentor
let filter = data.filter((e) => {
return e.mentor === "";
});
if (filter.length > 0) setStudents(filter);
} catch (err) {
console.log(err);
}
};
getStudents();
}, []);
const [assignedStudent, setAssignedStudent] = useState(students[1]);
const handleChange = (e) => {
setAssignedStudent(
students.find((student) => student._id == e.target.value)
);
console.log(assignedStudent);
};
const handleSubmit = async (e) => {
e.preventDefault();
console.log(assignedStudent);
}
<form onSubmit={(e) => handleSubmit(e)}>
<select onChange={handleChange} value={assignedStudent}>
{students.map((student) => {
return (
<>
<option key={student._id} value={student.id}>
{student.name}
</option>
</>
);
})}
</select>
<button type="submit">Submit </button>
</form>
2 जवाब
आपका विद्यार्थी ऑब्जेक्ट API कॉल से पहले खाली है और आपके setState
में इनिशियलाइज़ नहीं किया गया था। इसलिए अपने select
तत्व में students.map
का उपयोग करने से undefined
त्रुटि हो जाएगी।
इसे हल करने के लिए विकल्प हैं, उनमें से एक ?
if
के शॉर्टहैंड का उपयोग कर रहा है
{
students?.map(
// rest of your codes
)
}
यद्यपि आप अपने छात्रों ऑब्जेक्ट का आकार जांचने के बाद पुनरावृति कर सकते हैं (जो आपको बताता है कि डेटा API कॉल से आया है)
{
if(students.length > 0) {
students.map(
// rest of your codes
)
}
}
विकल्प मान _id होना चाहिए। अपने खोज में आप student._id
के साथ तुलना कर रहे हैं लेकिन विकल्प में आपके द्वारा पारित मूल्य प्रोप student.id
है, इसलिए रिटर्न अपरिभाषित खोजें
<option key={student._id} value={student._id}
{student.name}
</option>