React Update State

How to update state of an object

We have a user object

setUser({
  ...user,
  name: "Peter"
});

 

How to update state of list/array of objects

We have a shopping cart which contains a list of menu items

const [shopCart, setShopCart] = useState([{
  name: "",
  price: 0,
  uuid: ""
}]);


add item to shopping cart

const addMenuItemToCart = (menuItem: any) => {
  console.log("addMenuItemToCart, ", menuItem)

  setShopCart(shopCart => {
    shopCart.push(menuItem);
    const newState = shopCart.map(obj => {
      // 👇️ otherwise return object as is
      return obj;
    });

    return newState;
  });

}

 

 

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *