I have a table of items and want to allow the user to toggle a "favourites" checkbox that will add/remove the a favourites table. Since toggling the checkbox will add/remove the item from a state array called "favourites" (which is read from in the favourites table component), I am using the state favourites array to to set the checked property of each checkbox in order to maintain a persistent check when the state favourites array is updated and the page is reloaded:
<td><input type="checkbox" id={establishment.FHRSID} onChange={handleFavouriteClick} checked={favourites.some(favourite => favourite.BusinessName == establishment.BusinessName) ? true : false}></input></td>
The function that adds/removes the item from the state favourites array:
function handleFavouriteClick(){
if(document.getElementById(establishment.FHRSID).checked == true){
console.log('favourites: ', [...favourites, establishment])
setFavourites([...favourites, establishment]);
}else{
var temp_favourites = favourites;
var index = temp_favourites.findIndex(x => x.BusinessName === establishment.BusinessName);
if (index > -1) {
temp_favourites.splice(index, 1);
console.log('favourites: ', temp_favourites)
}
setFavourites(temp_favourites);
}
}
BUT doing it way is not allowing me to uncheck the checkbox. The item IS removed from the favourites array as I can confirm with console logs but the HTML checkbox is never reloaded when the item is removed from favourites but it does reload when the item is added.
Could anybody advice what I may be doing wrong?
Thanks