I couldn't get the idea of updating state in react.
state = {
products : []
};
handleProductUpVote = (productId) => {
const nextProducts = this.state.products.map((product)
=> {
if (product.id === productId) {
return Object.assign({}, product, {
votes: product.votes + 1,
});
} else {
return product;
}
});
this.setState({
products: nextProducts,
});
}
Why we need to clone the object? Can we simply write
if (product.id === productId) {
product.votes =
product.votes + 1;
});