Reputation: 141
I am building a simple checkbox component in React Native, I am trying to make some script to add and delete selected choice from an array of selected choices.
I am using the Array.filter()
function to check whether an item is in the array - however I get this error:
selected.filter is not a function.
(In 'selected.filter(function (c) {
return c === choice;
})', 'selected.filter' is undefined)
Here is my code:
const Select = ({ multichoice, isMultiple }) => {
const [selected, setSelected] = useState([])
const includes = choice => (
selected.filter( c => c === choice ).length
)
const toggleSelected = choice => {
if ( includes(choice) ) setSelected( selected.filter( c => c != choice ) )
else setSelected( selected.push(choice) )
}
return (
<View style={styles.selectContainer}>
{multichoice.map(choice =>
<Option choice={choice} toggleSelected={toggleSelected} selected={includes(choice)}/>
)}
</View>
)
}
Upvotes: 0
Views: 236
Reputation: 5766
When you call .push
on an Array, it returns what you pushed to the array, not the what the array you called the function on. So instead of
setSelected( selected.push(choice) )
use
setSelected([...selected, choice])
This will add the choice
to the end of your current selected
array and then update that with the hook.
Upvotes: 1