简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM