2

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.

1 Answer 1

2

The use of the function-based setter

setMenuList((prevMenuList)=>{

is useful when the function may be called when the menuList currently in its scope is not what's currently being rendered - for example, for when the function is called after an API call finishes. This is completely different from React's need to not mutate state, which requires another approach entirely.

Map the state array, and when the ID matches, return a new object with the amount incremented.

const onClickHandler = (id) => {
  setMenuList(
    menuList.map(
      obj => obj.id !== id ? obj : ({
        ...obj,
        amount: obj.amount + 1
      })
    )
  );
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.