useCartMutation
The useCartMutation hook is a specialized wrapper around useMutation that provides methods for modifying the shopping cart. It handles identifying the correct cartId for guest vs. registered users and automatically triggers a refetch of the cart data upon success.
import { useCartMutation } from 'shop/client/features/cart/hooks/useCartMutation';
const { addToCart, removeFromCart, isCartLoading, cartError } = useCartMutation(options);
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| options | MutateOptions<Cart> | Standard options for the useMutation hook. |
options
Standard mutation options. See MutateOptions for more information.
Return value
| Property | Type | Description |
|---|---|---|
| addToCart | (code: string, quantity?: number) => Promise<void> | Adds a product to the cart. |
| removeFromCart | (entry: CartEntry) => Promise<void> | Removes an entry from the cart. |
| updateCart | (entryNumber: number, product: Partial<CartEntry>) => Promise<void> | Updates a cart entry. |
| mergeCarts | () => Promise<void> | Merges guest cart with user cart. |
| clearCart | () => Promise<void> | Clears the current cart. |
| isCartLoading | boolean | True if a mutation is in progress. |
| isCartError | boolean | True if the last mutation failed. |
| cartError | DefaultResponseError | null | The error object if a mutation failed. |
| resetCartError | Function | Clears the current error state. |
Example
import { useCartMutation } from 'shop/client/features/cart/hooks/useCartMutation';
function AddProductButton({ productCode }) {
const { addToCart, isCartLoading } = useCartMutation();
const handleAdd = async () => {
await addToCart(productCode, 1);
alert('Added to cart!');
};
return (
<button onClick={handleAdd} disabled={isCartLoading}>
{isCartLoading ? 'Adding...' : 'Add to Cart'}
</button>
);
}