user23424
user23424

Reputation: 71

How to filter an element from an array in react native

I have created a function for removing an item from an array when the delete icon is pressed but the deletion is not working. Below is the code with the function that is supposed to filter an element from an array but it throws undefined is not an object(evaluating alerts.filter).

 const [alerts, setAlerts] = useState([])
  function itemRemove(item) {
        setAlerts(({ alerts }) => ({
            newalerts: alerts.filter(i => i.key !== item.key)
          }))
      }
 return (
    
        <ScrollView>
        {
          alerts  &&  alerts.map((item, i) => {
                return (
                    <ListItem key={i} bottomDivider>
                <ListItem.Content>
                    <ListItem.Title>

                        {item.CurrencyPair_Name}
                    </ListItem.Title>
                    
                    <MaterialCommunityIcons
                    name="delete"
                   onPress={() =>itemRemove(item)}
                
                    size={24}
                    color="black"
                    style={{position:"absolute", right: 3}}/> 
                </ListItem.Content>
            </ListItem>
                )
            }
            )
            
        }
        </ScrollView>
         
    )

Upvotes: 0

Views: 65

Answers (3)

undefined
undefined

Reputation: 441

const [alerts, setAlerts] = useState([])

function itemRemove(item) {
    const newAlerts = alerts.filter(i => i.key !== item.key);

    setAlerts(newAlerts);
}

Upvotes: 0

Nooruddin Lakhani
Nooruddin Lakhani

Reputation: 6967

Try this way

function itemRemove(index) {
    const newAlerts = [...alerts];
    newAlerts.splice(index, 1);
    setAlerts(newAlerts);
}


return (
   ........
   onPress={() =>itemRemove(i)}  // send index here               
   ......      
)

Upvotes: 0

Someone Special
Someone Special

Reputation: 13588

can u try this.

  function itemRemove(item) {
        setAlerts(prev => prev.filter(i => i.key !== item.key))
  }

You declared alerts as an array, not an object.

Upvotes: 1

Related Questions