0

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>
  )
}

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much, I missed that - it still doesn't seem to work. It is now giving the error Maximum update depth exceeded
If that's the case, then we will need to see more than the code you've posted here. I would suggest writing a new question because that is outside the bounds of this current question.
Now worries, looked like I have fixed it (mainly with your help) thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.