I have a checkboxes array with boolean values and I want to update its elements on change. Now instead of filled array [false, false, false, false, true] I get [empty × 4, true]
const [checkboxes, setCheckboxes] = useState([]);
const [listInfo, setList] = useState([]);
const getList = async () => {
const response = await list.get('/list/')
setList(response.data)
}
useEffect(() => {
const array = []
getList().then(() => {
for (let i = 0; i < listInfo.length; i++) {
array[i] = false
}
setCheckboxes(array)
})
}, [])
const handleChangeCheckbox = (event, i) => {
let isChecked = event.target.checked;
const array = []
if (isChecked) {
array[i] = true
setCheckboxes(array)
} else {
array[i] = false
setCheckboxes(array)
}
}
And I call this function:
<input key={i} type="checkbox" onChange={e => handleChangeCheckbox(e, i)}></input>
How to update elements correctly?
map()method. This answer should give you an idea of how you could do this.