Reputation: 9560
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;
});
Upvotes: 1
Views: 97
Reputation:
State updates can happen asynchronously, and delegating actual change of the state helps to ensure that things won't go wrong. Passing a new Object with the change also lets react make a (shallow) check to see which parts of the state were updated, and which components relying on it should be rerendered.
Upvotes: 1