[Solved] What are the different ways to add/update and remove the item from the State? [closed]

manojkarmocha Asks: What are the different ways to add/update and remove the item from the State? [closed]
handleAddToCart method does some conditional checks in cartItem state. First checks, if there is any item in array of object, if item exists, add 1 to it, or else just return item. Second check, if item does not exist add item and add 1 for the item ;

    const [cartItems, setCartItems] = useState([] as memePropsType[]);
    const handleAddToCart = (clickedItem: memePropsType) => {
     setCartItems((prev) => {

    // 1. Is the item already added in the cart?
    const isItemInCart = prev.find((item) => item.id === clickedItem.id);

    if (isItemInCart) {
      return prev.map((item) =>
        item.id === clickedItem.id
         ? { ...item, amount: item.amount + 1 }
         : item
      // First time the item is added
      return [...prev, { ...clickedItem, amount: 1 }];

    const handleRemoveFromCart = (id: string) => {
    setCartItems((prev) =>
      prev.reduce((ack, item) => {
         if (item.id === id) {
           if (item.amount === 1) return ack;
         return [...ack, { ...item, amount: item.amount - 1 }];
         } else {
           return [...ack, item];
     }, [] as memePropsType[])

Both works fine, but what would anyone do to achieve this in different way?

Ten-tools.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thank you, Ten-tools.