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)
}
CodePudding user response:
Because of genres.splice(indexOfTargetId, indexOfTargetId)
.
The second argument is the number of items that will be deleted.
Let's say the index is 3, so it will delete three elements after the third item in the array.
For your usecase the first item has index 0, so it will not delete it.
It should be genres.splice(indexOfTargetId, 1)
Then you need to return a copy of the array, to make the state update.
return [...genres]
CodePudding user response:
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
CodePudding user response:
const [genres, setGenres] = useState([])
const checkChange = event => {
const targetId = event.target.id
const indexOfTargetId = genres.indexOf(targetId)
//if condition check id is there or not and it's there then remove it
if (genres.includes(targetId)){
const filterId = genres.filter((item) => item !== targetId);
setGenres(filterId)
}
//else add this id
else{
setGenres([...genres, targetId])
}