CartContextProvider
A React context for a cart object: wrap part of the page once, then read the cart anywhere inside it with useCartContext().
import { CartContextProvider, useCartContext, CartContext, CartContextValue, CartContextProviderProps } from '@salla.sa/twilight-theme-engine/contexts';In plain words
The same idea as the product context, for a cart: <CartContextProvider value={{ cart }}> around part of the page, then useCartContext() inside returns { cart }, or null outside a provider.
You supply the cart. The context does not fetch it or keep it up to date.
Signature
interface CartContextValue {
cart: Cart;
}
interface CartContextProviderProps {
children: ReactNode;
value: CartContextValue;
}
function CartContextProvider(props: CartContextProviderProps): React.ReactElement
function useCartContext(): CartContextValue | null
const CartContext: React.Context<CartContextValue | null>Example
import { CartContextProvider, useCartContext } from '@salla.sa/twilight-theme-engine/contexts';
import type { Cart } from '@salla.sa/twilight-theme-engine/types';
function ItemCount() {
const context = useCartContext();
return <span>{context?.cart.count ?? 0} items</span>;
}
export function CartSummary({ cart }: { cart: Cart }) {
return (
<CartContextProvider value={{ cart }}>
<ItemCount />
</CartContextProvider>
);
}
How it behaves
A plain React context that nothing in the engine reads. It memoizes its value on
value.cart: pass a new cart object when the cart changes, or consumers keep the old one.CartContextitself is exported foruse(CartContext)and class components.
Gotchas
Like the product context, its source comment says
HookSlotinjects it intocart:*handlers; it does not. Passcontext={{ cart }}to the slot.
Related
Source and docs
- Engine source:
packages/theme-engine/src/contexts/CartContext.tsx