I don't quite understand this function, like what do you filter out and the way it work...can anybody help me to expalin this? I'm a begginer and i need your help! Thank you so much btw!
Function:
removeFromCart =(product) => {
const cartItems = this.state.cartItems.slice()
this.setState({
cartItems: cartItems.filter((x)=>x.id!==product.id)
})
}
CodePudding user response:
Array.prototype.filter
expects a callback that returns a boolean.
If the callback returns true
, the element gets pushed to the new array and if it returns false, the element will not be pushed.
const cartItems = this.state.cartItems.slice()
creates a new array and can be removed as filter
creates a new array anyway.
cartItems.filter((x)=>x.id!==product.id)
If we consider the above snippet, the returned value is x.id!==product.id
because if the id matches, x.id !== product.id
will evaluate to false
and returning false
will remove the product.
CodePudding user response:
This is the longer version of that code, you might get confused because your version has a lot of shortcuts and bad variable name. (comments)
removeFromCart = (product) => {
const cartItems = this.state.cartItems.filter((item) => {
return item.id !== product.id;
});
this.setState({
cartItems: t
})
}
let's know this:
const cartItems = this.state.cartItems.slice()
First, you don't need this one as filter
already returns a new array
usually you use slice
to create a copy (portion) of that array (usually we pass arguments on it and I've rarely seen a usage where the dev uses it as a "clone" function. You can read more about it here.
const cartItems = this.state.cartItems.filter((item) => {
return item.id !== product.id;
});
for this one, I renamed your variable x
into item
to make it more understandable. Since cartItems
is an array, this function will go through each items then create a new array where the item id is not the same as product id (return item.id !== product.id). Read more about filters here
this.setState({
cartItems
})
you pass the newly created cartItems
to update your state.