Trying to delete a property in an array that is also within in array in React
You're close. You're just missing reassignment of shoe.list
with updated list of shoes after filtering.
deleteShoe = (id) => {
const { shoeList } = this.state;
const newShoeList = shoeList.map(shoe => {
shoe.list = shoe.list.filter(shoeid => shoeid.id !== id)
return shoe;
});
this.setState({
shoeList: newShoeList
})
}
This should remove appropriate shoe id and reassign your shoe.list
with newly filtered shoes list.
Related videos on Youtube
Richard Desouza
Updated on December 17, 2022Comments
-
Richard Desouza over 1 year
I'm trying to add functionality to my application for deleting values in the list array of the following state
shoeList : [ {name: 'Nike', list : [ {type: 'boots', revenue: '1000000', gender: 'mens', price: '49.99', id: 3}, {type: 'shoes', revenue: '13280100', gender: 'womens', price: '99.99', id: 2} ] } ],
I understand that ids have to be equal in order for a deletion to occur. Right now i'm trying to access the appropriate row to be deleted(type, revenue, gender, and price) but am not sure how to access properties in an array thats within an array.
Here is the code i have so far
deleteShoe = (id) => { let shoeList = this.state.shoeList.filter(shoe =>{ return ( shoe.list.filter(shoeid =>{ return shoeid.id !== id } ) ) }); this.setState({ shoeList: shoeList }) }
Obviously this code doesn't and can't understand why. The only reason I can think of is that filter can't be nested but if so how would I go about implementing this. Any help would be great
-
Richard Desouza about 4 yearsThanks for the help!
-
Edgar Henriquez about 4 yearsBecause
this.setState
is asynchronous, when you're updating the state based on the previous state is best to pass a function, instead of an object... Something like thisthis.setState ((prevState) => {//Do your logic and return your state})
.