0

This function is responsible for updating the item quantity , first fetching the localStorage , then if the item exists update its quantity, and update the localStorage as well.The thing i don't understand here as exist is a different object , and i am updating its quantity ,why the cart gets updated with new quantity

const increaseQty = (id: number) => {
        const cart9 = getCartFromLocalStorage();
        const exist = cart9.find((item: any) => item.id === id);
        if (exist) {
          exist.quantity += 1;
          console.log({ exist, cart9 });
    
          localStorage.setItem("cart", JSON.stringify(cart9));
          getCartFromLocalStorage();
        }
      };
Nick Jonas
  • 103
  • 1
  • 7
  • 5
    The exist object is a reference to an object in cart9, so if you update exist, to pointed data that is also referenced in cart9 will be updated to. `find` returns reference, not copy. And in general objects are referenced and not copied, unless using an operator like `cpy= {...myobj}` – Peterrabbit Jun 20 '23 at 04:40

0 Answers0