useCartItemQuantity
The useCartItemQuantity
hook is a React hook designed to add, delete or update items in the cart.
Usage
The useCartItemQuantity
hook provides methods and values to manage the quantity of a specific product variant in a shopping cart.
import { useCartItemQuantity } from builderoo
const { add, remove, set, quantity } = useCartItemQuantity(product, variant)
Parameters
Name | Type | Description |
---|---|---|
variant | object | The product object to which the quantity management will be applied. |
variant | object | The specific variant of the product for which the quantity will be managed. |
Return Values
Name | Type | Description |
---|---|---|
quantity | number | The current quantity of the specified product variant in the cart. |
add | function | A function to increase the quantity of the specified product variant in the cart. |
remove | function | A function to decrease the quantity of the specified product variant in the cart or remove it entirely if the quantity reaches zero. |
set | function | A function to set the quantity of the specified product variant to a specific value. |
Example
Here’s an example of how to use the useCartItemQuantity
hook in a product component:
import React from 'react';
import { useCartItemQuantity } from "builderoo";
function Product({ product, variant }) {
const { add, remove, set, quantity } = useCartItemQuantity(product, variant);
const addToCart = () => {
add(1).then(() => {
// do something when successful.
}).catch((e) => {
// do something when failed to add to cart.
})
}
return (
<div className="cart-item">
<h3>{product.name}</h3>
<button onClick={addToCart}>Add</button>
</div>
);
}
export default CartItem;