Skip to main content

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

NameTypeRequiredDescription
optionsMutateOptions<Cart>Standard options for the useMutation hook.

options

Standard mutation options. See MutateOptions for more information.

Return value

PropertyTypeDescription
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.
isCartLoadingbooleanTrue if a mutation is in progress.
isCartErrorbooleanTrue if the last mutation failed.
cartErrorDefaultResponseError | nullThe error object if a mutation failed.
resetCartErrorFunctionClears 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>
);
}