useCart
The useCart hook is a specialized wrapper around useFetch used to retrieve the current user's shopping cart. It works on the client as well as on the server. It automatically uses the cartId from useCartId and handles error states by clearing invalid cart identifiers if necessary.
import { useCart } from 'shop/client/features/cart/hooks/useCart';
const { data: cart, isLoading, error } = useCart(options);
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| options | FetchOptions | Standard options for the useFetch hook. |
options
Standard data fetching options. See FetchOptions for more information.
Return value
| Property | Type | Description |
|---|---|---|
| data | Cart | null | The current cart data. |
| error | DefaultResponseError | null | Error information if the fetch failed. |
| isLoading | boolean | True if the cart is being loaded. |
| isDone | boolean | True if the loading process is finished. |
| refetch | Function | Triggers a manual refresh of the cart data. |
Example
import { useCart } from 'shop/client/features/cart/hooks/useCart';
function CartBadge() {
const { data: cart, isLoading } = useCart();
if (isLoading || !cart) return null;
return (
<div className="badge">
{cart.totalItems} items - {cart.totalPrice.formattedValue}
</div>
);
}