I used useEffect to fetch an API and dynamically generate several checkboxes. I used onChange to change their state in an array. However, when I click on a checkbox, it does not change its checked or unchecked state. I need to click another static checkbox first to make the previous checkbox change its state. Here is my code.
<div className="fullinput list_checkbox_inline">
<SubmitOrg
localCheckBoxChange={handleorg}
editMod={editMod}
ref={submitOrgRef }
/>
</div>
import React, { Component, useEffect, useState, forwardRef, useImperativeHandle } from 'react';
const SubmitOrg = forwardRef((props, ref) => {
const [OrgList, setOrgList] = useState();
const [checkState, setCheckState] = useState(false);
const [movieOrg, setMovieOrg] = useState([]);
useImperativeHandle(ref, () => ({
setChildInitValData() {
InitValData()
}
}))
async function InitValData() {
if (props.editMod != null) {
let myarray = OrgList;
let refarray = props.editMod.tbl_image_movie_contentinvolveorg
if (refarray != null) {
for (let i = 0; i < myarray.length; i++) {
let localkid = myarray[i].cbval;
let y = refarray.filter(element => element.imc_orgcd === localkid);
if (y.length > 0)
myarray[i].ischecked = "checked"
}
setOrgList(myarray)
}
}
}
useEffect(() => {
GetOrgList();
}, []);
async function GetOrgList() {
const response = await fetch('/api/GetOrgCode/GetOrgDataCheckBox');
const data = await response.json();
setOrgList(data);
props.localCheckBoxChange(data)
}
async function CheckBoxChange(e) {
var mycheckval = e.target.getAttribute('val')
var myischecked = e.target.checked
let operkey = e.target.getAttribute('data-id')
let myarray = OrgList;
for (let i = 0; i < myarray.length; i++) {
let localkid = myarray[i].cbval;
if (localkid == operkey) {
if (myischecked)
myarray[i].ischecked = "checked"
else
myarray[i].ischecked = ""
}
}
props.localCheckBoxChange(myarray)
setOrgList(myarray)
//document.getElementById("chk_org_99").click();
}
const handleSelectChange = (event) => {
const value = event.target.value;
const checked = event.target.checked;
setCheckState(checked)
};
const CateContents = OrgList === undefined ?
<><p>Loading...</p>
</>
:
<>
<div className="fullinput list_checkbox_inline">
<input data-id="99" id="chk_org_99" type="checkbox" name="chk_org_99" onChange={(event) => handleSelectChange(event)} checked={checkState} />
<label for="chk_org_99">test</label>
</div>
{OrgList.map(items =>
<>
<input data-id={items.cbval} key={items.cbval} id={'chk_org_' + items.cbval} type="checkbox" name={'chk_org_' + items.cbval} val={items.cbval} onChange={CheckBoxChange} checked={items.ischecked==='checked'} />
<label key={'lbl_org_' + items.cbval} htmlFor={'chk_org_' + items.cbval}>{items.cbval}</label>
</>
)}
</>
return (<>{CateContents}</>)
})
export{ SubmitOrg };
I need to click another static checkbox first to make the previous checkbox change