useCartClient (Events)
The useCartClient hook provides low-level access to the CartClient instance, which extends SubscriberMap. This allows you to subscribe to real-time cart events and react to them in your application, providing a powerful way to build a responsive and interactive experience.
import { useCartClient } from '@archibald/commerce/cart';
const cartClient = useCartClient();
Return value
- Type:
CartClient
The CartClient instance provides the following subscription methods:
| Method | Description |
|---|---|
| subscribe | Listens for specific cart events and executes a callback. |
| publish | Manually triggers an event (rarely used in application code). |
Main Events
'cart': Fired whenever the cart is updated. Receives(cart, previousCart)as arguments.'error': Fired when an error occurs during a cart operation.
Example
import { useEffect } from 'react';
import { useCartClient } from '@archibald/commerce/cart';
function CartNotification() {
const cartClient = useCartClient();
useEffect(() => {
const unsubscribe = cartClient.subscribe('cart', (cart, previousCart) => {
if (cart.totalItems > (previousCart?.totalItems ?? 0)) {
console.log('Item added to cart!');
}
});
return () => {
unsubscribe();
};
}, [cartClient]);
return null;
}