I'm trying to update an array property in an array of objects using react hooks, as we all know when we need to update the state based on a previous state we use the function set"MypopertyName" as shown below:
My code:
const [MenuList, setMenuList] = useState([
{
id: 0,
title: "sushi",
desc: "finest fish and vegies",
price: "$22.99",
amount: 1,
},
{
id: 1,
title: "shneitzel",
desc: "a german specialty",
price: "$50.99",
amount: 1,
},
{
id: 2,
title: "pizza",
desc: "an italian specialty",
price: "$100.99",
amount: 1,
},
{
id: 3,
title: "pasta",
desc: "an italian specialty",
price: "$200.99",
amount: 1,
},
]);
my problem that I wanna change the amount of the meal based on clicks of the user so here is what I tried:
const onClickHandler = (id) => {
for (const key in MenuList) {
if (MenuList.id === id) {
return (MenuList[key].amount = MenuList[key].amount + 1);
}
}
};
I know that the reactivity system of react only works when I call setMenuList() I tried that but it doesn't work besides I wanna update the specific object immutably so I need to use the function syntax like this:
setMenuList((prevMenuList)=>{
//my code
})
also, I didn't manage to get it work, sorry guys I'm one of the old gurus that used the class-based components for a long time you know with the state={} and so on the whole new hooks concept is new for me.
So any help would be appreciated and thank you in advance.