Henok Tesfaye
Henok Tesfaye

Reputation: 9560

Updating state in react

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

Answers (1)

user6019272
user6019272

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

Related Questions