Reputation: 3228
I'm using react hooks, state within my component. A list of options is available to the user to select. I need tokeep track of which options have been selected - see "selectedArr" in state.
Whilst this partially works, filtering the selectedArr is buggy and won't filter if I select the second item in the options first? I don't understand why.
How can I keep track of which options are selected and toggle an individual option?
Here is my code
const BarGraph = ({graphData, daysRange}) => {
const [optionsIndex, setOptionsIndex] = useState(0);
const [selectedArr, setSelectedArr] = useState([]);
const toggleActiveItem = (index) => {
//Update the option index
setOptionsIndex(index);
//Update selected options array
setSelectedArr([...selectedArr, index])
if(index === selectedArr[index]) {
//Prevent from adding multiple of the same index
setSelectedArr([...selectedArr])
//if index is equal to the selected array index
//removed the matched index from selected array
setSelectedArr(selectedArr.filter((i) => i !== index));
}
}
Upvotes: 1
Views: 1428
Reputation: 1608
const toggleActiveItem = (index) => {
if(selectedArr.includes(index)){
setSelectedArr(selectedArr.filter((i) => i !== index))
} else {
setSelectedArr([...selectedArr, index])
}
setOptionsIndex(index)
}
Upvotes: 3