Reputation: 488
I have a somewhat todo list interface involving a shopping list which lets the user enter an item and the each item is displayed using a ScrollView being mapped by Array.map() however when I select on an individual item to be deleted the entire list deletes. I can't seem to find the problem as each individual key prop is unique.
The code:
let j = 1
const [ingriList, setIngriList] = useState([])
const [ingri, setIngri] = useState('')
const deleteItem = (key) => {
const filteredItems = ingriList.filter(item => item.key !== key)
setIngriList(filteredItems)
}
const handleSubmit = () => {
return (
setIngri(''),
ingri.length === 0
? <Text/>
: setIngriList(ingriList.concat(ingri))
)
}
return(
<View style = { styles.ingriContainer }>
<View style={styles.addPhotoCont}>
<TextInput
style={styles.textInput}
placeholder={'Add Something'}
onChangeText={item => setIngri(item)}
value={ingri}
/>
</View>
<View>
<TouchableOpacity onPress={handleSubmit}>
<Text style={styles.addButton}>Add</Text>
</TouchableOpacity>
</View>
<ScrollView>
{ingriList.map(i =>
(
<View key={j++}>
<Text style={styles.ingridientValues}>{i}</Text>
<View style={styles.cancel}>
<TouchableOpacity onPress={() => deleteItem(ingriList.key)}>
<MaterialIcons name="cancel" size={30} color={Colors.orange} />
</TouchableOpacity>
</View>
</View>
)
)
}
</ScrollView>
</View >
)
I would really appreciate it from the bottom of my heart if someone could help me with figuring out why the entire list is being deleted instead of the selected item. Thank you in advance!!!!!
Upvotes: 0
Views: 75
Reputation: 315
In your code, ingriList
is a list of strings, since you are calling setIngriList
as follows:
setIngriList(ingriList.concat(ingri))
Now when you attempt to delete an item from this list, you call deleteItem(ingriList.key)
, but ingriList.key
is undefined
. Finally, in deleteItem
, you are filtering out entries that match the key attribute, but since the key
attribute is undefined
for each element, all of the entries match and ingriList
is set to an empty array. This is most likely why you observe that all elements are deleted.
Try keeping a unique identifier for each 'ingri' in your ingriList
, by making it a list of objects instead:
const handleSubmit = (ingriId, ingri) => {
const newIngriList = ingriList.concat({ id: ingriId, val: ingri })
setIngriList(newIngriList)
}
const deleteItem = (ingriId) => {
setIngriList(ingriList.filter(ingri => ingri.id !== ingriId))
}
Each entry in your ingriList
needs to have a unique id
attribute that you can them pass to the deleteItem
function that will then remove it from the array.
Upvotes: 1