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;
});
}