I'm new in React so i faced this problem and i don't understand why this is happening , I created Component called ShoppingCart which display all the products that i added to the cart: ShoppingCart.jsx file:
import React, { Component } from 'react';
import Product from './Product';
class ShoppingCart extends Component{
state={
products:[
{
id:1,
name:"Burger",
count:2
},
{
id:2,
name:"Cola",
count:3
},
{
id:3,
name:"Fries",
count:4
}
]
}
deleteProduct=(product)=>{
let newProducts = this.state.products.filter((p)=>
{ return p.id !== product.id}
);
this.setState({products:newProducts});
}
reset = ()=>{
let resetProducts = this.state.products.map((p)=>
{ p.count = 0; return p}
);
console.log(resetProducts);
this.setState({products:resetProducts});
}
render(){
return(
<div>
<h1>Products</h1>
<button onClick={this.reset}>reset</button>
{this.state.products.map((product)=>{
return <Product key={product.id} onDelete={this.deleteProduct} product={product}/>
})}
</div>
);
}
}
export default ShoppingCart;
also i have component called Product holds the product details such as : id,name and the counter:
import React, { Component } from 'react';
class Product extends Component {
state = {
id: this.props.product.id,
name: this.props.product.name,
count: this.props.product.count
}
render() {
return (
<div>
<span>{this.state.name}</span>
<span>{this.state.count}</span>
<button onClick = {()=>this.props.onDelete(this.props.product)}>Delete</button>
{/* Ensure onDelete is used correctly */}
</div>
);
}
}
export default Product;
Now my problem is when i try to delete any product it is deleted and the new list of items is rendered in the page but when i try to reset the counter of the elements it is reset but the new list isn't rendered to the page. So can someone help me to understand how it works ?
Here is some sample code I put together which I think is inline with what you've included in your original question:
Also, here is another example of a similar behaviour, maybe this can be of some help:
https://www.robinwieruch.de/react-remove-item-from-list/