I am mapping some data into a table. Each row of the table has a checkbox. In order to manage the state of the checkboxes I am adding or removing the checkbox id to the array.
I want to determine if a box should be checked by seeing if the id is contained in the array.
const [bulkUpdateIds, setBulkUpdateIds] = useState([
'7a678176-2703-4f89-63cb-08dc3e4b1e2f',
])
function handleCheck(id) {
console.log('running', bulkUpdateIds)
const idArray = bulkUpdateIds
if (idArray.includes(id)) {
const index = idArray.indexOf(id)
idArray.splice(index, 1)
setBulkUpdateIds(idArray)
} else {
idArray.push(id)
setBulkUpdateIds(idArray)
}
}
cellRenderer: (params) => {
return (
<input
type="checkbox"
checked={bulkUpdateIds.includes(
params.data.soVRecordID
)}
onChange={() =>
handleCheck(params.data.soVRecordID)
}
/>
)
},
I can see that the id is being added and removed from the list, however it seems like the logic to determine if the box is checked or not only fires once.
2
Answers
Consider creating a new array to
setBulkUpdateIds
, instead of mutating the existing array value. As per the documentation:Thus, we tweak the logic in
handleCheck()
to avoid array mutation and instead pass a whole new array value each time:Wongjn has explained it well.
However, a quick fix in your case would be replacing the
const idArray = bulkUpdateIds;
withconst idArray = bulkUpdateIds.slice(0);
This will make a copy of ‘bulkUpdateIds’ for further processing.So the new
handleCheck()
would be-