Home > Blockchain >  Function returns undefined when using event.target.value in find(), but works when setting useState
Function returns undefined when using event.target.value in find(), but works when setting useState

Time:01-17

I'm struggling with a strange issue. I have a select component that passes a value called "classID" up to a useState. I have an array mapped over the select component that looks like this (sent from NodeJS API):

[{classID: 371, teacherID: 1, subjectID: 3, subjectTitle: 'Mathematics', subjectLevel: 'IGCSE Level', …}, {classID: 370, teacherID: 1, subjectID: 2, subjectTitle: 'Physics', subjectLevel: 'IGCSE Level', …}]

Each object contains a "classID", "subjectID" etc. Here are the states:

  const [classID, setClassID] = useState("");
  const [subjectID, setSubjectID] = useState("");

The classID is set with a useState variable during onChange within the select component:

<CFormSelect className="pointer" onChange={setClass} value={classID}>
  <option value="">Select A Class</option>
  {classOption.map((c) => (
    <option key={c.classID} value={c.classID}>
      {c.subjectTitle} {c.subjectLevel} ({c.syllabusCode} - {c.classIdentifier})
    </option>
  ))}
</CFormSelect>;

Which feeds into this function:

const setClass = (event) => {
    console.log(event.target.value);
    setClassID(event.target.value);
    setClassID(event.target.value);
    let result = classOption.find(
      (item) => item.classID === event.target.value
    ).subjectID;
    console.log(result);
  };

What I am trying to do is use the "event.target.value" (which is classID) to set the classID state variable, and then use it again to find the subjectID element within the object that has the classID === event.target.value (as per the array shown above). I would then like to set "subjectID" to the subjectID element that the function returns.

The function, however, returns undefined. If I manually replace "event.target.value" in the find() function with a hardcoded classID, the function returns the correct subjectID. As soon as I try to do the same with "event.target.value", the function returns undefined. What's strange is that event.target.value returns with the correct value when I console.log

For some reason the find() function doesn't accept it.

Please let me know if I can offer any other code/information. I'd greatly appreciate any assistance

CodePudding user response:

use == rather than === for your code " item.classID === event.target.value "

For plenty of information: Which equals operator (== vs ===) should be used in JavaScript comparisons?

  • Related