I have a series of checkboxes that when clicked will populate an array with the id of that checkbox. When unclicked it will remove the id from the array and so forth. It all works well except for one strange behavior. Whatever the first checkbox I click (which will become the first entry in the array) I can never remove. For some reason the first element of the array can never be removed.
Here is my handler that is triggered whenever there is a change on one of the checkboxes.
const [genres, setGenres] = useState([])
const checkChange = event => {
const targetId = event.target.id
const indexOfTargetId = genres.indexOf(targetId)
if (indexOfTargetId === -1)
setGenres([...genres, targetId])
else genres.splice(indexOfTargetId, indexOfTargetId)
}
You'd want to set the state again in that else
rather than simply splicing the array in state. I've made a couple of modifications to the code.
const [genres, setGenres] = useState([])
const checkChange = event => {
// Destructure the id from the target
const { id } = event.target;
const index = genres.indexOf(id);
if (index === -1) {
setGenres([...genres, id])
} else {
// Make a copy of the state
const copy = [...genres];
// `splice` out the offending id
copy.splice(index, 1);
// Set the state with the spliced array
setGenres(copy);
}
}
Additional documentation