Home > Blockchain >  How to populate select option using api
How to populate select option using api

Time:10-03

Here is my code. I am getting student's data from backed, filtering it. I am not able to set the default value for the select option and neither is setAssignedStudent working, in the console, I am getting undefined. Please let me know how to fix this.

//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>

CodePudding user response:

your students object is empty before the API call and was not initialized in your setState. so using students.map in your select element will cause the undefined error.

there are options to solve this, one of them is using ? shorthanded of if

{
  students?.map(
    // rest of your codes
  )
}

Although you can iterate over your students object after checking its size(which tell you the data has arrived from API call)

{
  if(students.length > 0) {
     students.map(
        // rest of your codes
     )
  }
}

CodePudding user response:

The option value should be _id. In your find you are comparing with student._id but in the option the value props you passed is student.id that's why find returns undefined

<option key={student._id} value={student._id} 
   {student.name}
</option>
  • Related