Updating state using setState on onChange functionality of the input Form crashing the page. setState not Updating state

Viewed 18
const RoomAttendanceComponent = () => {
 const [formData, setFormData] = useState({});
 const [optionalIds, setOptionalIds] = useState([]);
let ids = []

const fetchAttendanceCriteria = (updatedFormData) =>
     updatedFormData.classRoomNo && updatedFormData.selectedDay &&
     (formData.classRoomNo !== updatedFormData.classRoomNo ||
         formData.selectedDay !== updatedFormData.selectedDay);

const fetchAttendance = async (updatedFormData) => {
     const response = await fetchAttendanceData(updatedFormData);
     getAttendanceResults(response);
     setFormData(updatedFormData);
};
const onChange = async ({ formData: updatedFormData, errors }) => {
     if (fetchAttendanceCriteria(updatedFormData)) {
         await fetchAttendance(updatedFormData);
     }
     if(updatedFormData.membersId){
     ids = formatMembersId(formData.membersId);
     setOptionalIds(parseInt(ids))
     }
 };

const updatedPresentIds = (presentIds) => {
     if (presentIds) {
         ids = [...optionalIds, ...presentIds];
     }
     return ids;
 };

 
return (
<RoomAttendaceGridComponent />
<RoomAttendanceFormCompoenent />
)
}

updatedFormData.membersId gives me the id such as {'67', '6', '5'} which is what user has typed in the input field. But for some reason updating the setOptionalids state on the onChange functionality is breaking the pages.

1 Answers

As the ids is an array, so you should parseInt the element of ids by mapping like this ids = ids.map(x => parseInt(x)); Then add it to setOptionalIds. I guess you are getting an error for parseInt. If you can explain a bit more about it, then it will be clear

Related