adrianhajdin / ecommerce_sanity_stripe

Modern Full Stack ECommerce Application with Stripe

Home Page:https://jsmastery.pro

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Product quantity does not revert back to initial state " 1 "

F00r3y3s opened this issue · comments

Hi,

The issue i want to solve is the product quantity does not update back to 1 once i move to a different product after adding current product to the cart

the issue can also be seen in the tutorial video

at 2:35:44 to 2:35:51

Product A quantity 5
Product B quantity still 5

I solved this by adding a const [quant, setQuant] = useState(1); to [slug].js
using the router component : import { useRouter } from "next/router";
and I used it inside to detect URL change the useEffect hook:

Capture4

then I moved the functions incQty and decQty to [slug].js file and removed their definition from the useStateContext export and destructure

Capture5

finally I started using { quant } instead of { qty }

well, this worked but I'm only a begginer so I hope some expert would enlighten us with a better solution

commented

[StateContext.js]

const initQty = () => {
        setQty(1);
 }
 <Context.Provider
            value={{
                showCart, cartItems, totalPrice, totalQuantities, qty, setShowCart,
                incQty, decQty, initQty, onAdd, toggleCartItemQuantity, onRemove
            }}
   >

[product.js]

   import { useStateContext } from '../context/StateContext';
   const Product = ({ product : {image, name, slug, price}}) => {
  const { initQty } = useStateContext();
  return (
    <div>
      <Link href={`/product/${slug.current}`} >
        <div className="product-card">
          <img 
            src = {urlFor(image && image[0])}
            width = {250}
            height = {250}
            className = "product-image"
            onClick={initQty}
          />
          <p className='product-name'>{name}</p>
          <p className='product-price'>${price}</p>
        </div>
      </Link>
    </div>
  )
}

Hope this helps