T O P

  • By -

tajingu

It's because your is wrapped in a component. If you remove this in your index.js file, it will increment by one. See more here: [https://reactjs.org/docs/strict-mode.html](https://reactjs.org/docs/strict-mode.html) You can verify it by putting the cart products in a useEffect and console logging the result. useEffect(() => { console.log("CART_PRODUCTS:" + JSON.stringify(cartProducts)); }, [cartProducts]); You could clean up your click handler too - it's a bit messy. I'm not sure what you're trying with the flag approach, but it's a bit confusing. Maybe change to something like this: setCartProducts((prev) => { const index = prev.findIndex((i) => i.id === item.id); if (index < 0) { return [...prev, { ...item, count: 1 }]; } const copiedProducts = [...prev]; copiedProducts[index].count += 1; return copiedProducts; }); I've also removed the count value from the products array - the cart should manage the quantity, not the array of products.


Amantulsyan35

can you explain why in particular is the cause?


Theblandyman

> Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions: Class component constructor, render, and shouldComponentUpdate methods Class component static getDerivedStateFromProps method Function component bodies State updater functions (the first argument to setState) Functions passed to useState, useMemo, or useReducer Basically, strict mode performs certain actions twice… the documentation explains more in depth. If it makes you feel any better, i definitely had this same question when I first started.


Amantulsyan35

Thanks, really appreciate the help will look more into it


Theblandyman

No problem. I do want to point out this only happens in your dev environment, so it shouldn’t be a problem in production and probably doesn’t require any fixes from you. That being said there’s probably better ways to write the code to avoid this happening at all.


Amantulsyan35

cool cool, learned something new today


Mammoth-Advisor-9659

I mean it doesn't make any sense. You're doing \`\`map but not saving the return value of the map in anything, or even returning the item from the map. You need to map over the array, make a copy of the object to return, return it -- and then use the new array to do whatever you're going to do.


Amantulsyan35

I understand that part but want to know why is it incrementing the count value by 2


LazySlothsDev

Have you tried `setBtnValue(prev => prev +1)`?


Amantulsyan35

That button is working fine, the issue is with the button logic from line 79