Reputation: 71
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
Reputation: 441
const [alerts, setAlerts] = useState([])
function itemRemove(item) {
const newAlerts = alerts.filter(i => i.key !== item.key);
setAlerts(newAlerts);
}
Upvotes: 0
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
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