Reputation: 157
when I click in the checkbox of the table row, I am updating the array selecteddata with id and after that I am passing the checked value by finding whether id exists in the selecteddata to check the checkbox. I am able to store the id in selectedData but it is not showing instance changes in checkbox.
const [selectedData, setSeletcedData] = useState([]);
const handleCheckboxSelect = (id) => {
setHasSelectedAll(false);
setSeletcedData((selectedData) => {
if (selectedData.includes(id)) {
return selectedData.filter((currentId) => id !== currentId);
} else {
selectedData.push(id);
return selectedData;
}
});
};
<CDataTable
items={matter}
fields={fields}
hover
pagination
count: (item) => (
<CFormGroup variant="checkbox" className="checkbox">
<CInputCheckbox
id="checkbox1"
name="checkbox1"
value="option1"
checked={selectedData.includes(item.id)}
onChange={(e) => handleCheckboxSelect(item.id)}
/>
</CFormGroup>
),
}}
/>
Upvotes: 1
Views: 96
Reputation: 12787
Use spread operator
to return new Array instead push
else {
return [...selectedData, id];
}
Upvotes: 1
Reputation: 516
You're returning the same array reference in the line
selectedData.push(id);
return selectedData;
which won't cause the component to re-render, you should return a new array with the new item with, using spread operator
or Array Cloning
spread operator
:
return [...selectedData,id];
Cloning
:
const newArray = Array.from(selectedData);
newArray.push(id);
return newArray;
Upvotes: 1