so i have a store that looks like this:
export class NoteStore {
notes = [
{
id: 1,
name: 'Shopping list',
children: [
{
id: 2,
name: 'Sweet',
items: [
{
id: 3,
name: 'Chocolate',
},
{
id: 4,
name: 'Fudge'
},
{
id: 5,
name: 'Cookies'
}
]
}
]
}
}
i am trying to remove an item from items by pressing a button. so far i have managed to make a remove function that does not throw an error but it doesn't do anything. i have spent so much time with this but i just can't figure out what i need to do to get the removing working properly. this is what i'm working with:
const store = useContext(NoteStore);
function removeItems(id) {
store.notes = store.notes.filter(item => item !== id);
}
//Prints notes content to the screen
const NotesArray = () => {
return store.notes[0].children[0].items.map((item) =>
<View key={item.id} style={{ flexDirection: 'row' }}>
<Text style={styles.note}>{item.name}</Text>
<TouchableOpacity style={{ justifyContent:'center', paddingLeft:5 }} onPress={() => {
removeItems(item.id);
}}>
<Text>
<Icon name={noteDeleteMode ? 'close-circle-outline': null} style={styles.deleteIcon} />
</Text>
</TouchableOpacity>
</View>
)
};
You currently comparing the id
with the whole item
, not with it's id
.
Replace
store.notes = store.notes.filter(item => item !== id);
with
store.notes = store.notes.filter(item => item.id !== id);
( item.id
instead of just item
)
Probably the issue is that you're saving the reference to the old store.notes
somewhere. Fortunately, you don't need to create a new array; you can just modify the old one. Use this:
function removeItems(id) {
store.notes.splice(store.notes.findIndex(item => item.id === id), 1);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.