Skip to main content

Cart, wishlist and comparison

By the end of this page

You can drive the cart from your own components and trust the totals the checkout uses.

useCart​

import { useCart } from '@neverleans-labs/plug-store-core';

function AddToCart({ product }) {
const { addItem, itemCount } = useCart();

return (
<button onClick={() => addItem(product, 1)}>
Add to cart ({itemCount})
</button>
);
}
MemberTypeNotes
itemsCartItem[]{ product, quantity, selectedVariants? }
addItem(product, quantity?, variants?) => voidAdding the same product and variants increases the quantity
removeItem(productId) => void
updateQuantity(productId, quantity) => voidZero removes the line
clearCart() => voidCalled automatically after a successful checkout
itemCountnumberSum of quantities, not distinct lines
subtotalnumberLine prices × quantities
discountnumberAmount removed by the applied coupon
shippingCostnumber
totalnumbersubtotal − discount + shippingCost
discountCodestringCurrently applied coupon code
setDiscountCode(code) => voidValidates against the configured coupons
Use total, never recompute it

total already includes discount and shipping. A checkout screen that adds shipping on top of total charges it twice — which is exactly the bug the built-in checkout page once had.

useWishlist​

const { items, addItem, removeItem, isInWishlist, toggleItem } = useWishlist();

toggleItem(product) is what the heart button on ProductCard calls. isInWishlist(productId) returns a boolean.

useCompare​

const { items, toggle, remove, clear, has, isFull } = useCompare();

The comparison list is capped; isFull tells you when adding another would be rejected, so you can disable the control instead of failing silently. The /compare route renders a side-by-side table of whatever is in the list, and CompareBar is the floating summary bar.

useRecentlyViewed​

const { items, add, clear } = useRecentlyViewed();

ProductDetailPage calls add(product) on mount. RecentlyViewedRow renders the strip.

Persistence​

All four persist to localStorage and rehydrate on the next visit:

HookKey
useCartecom-cart
useWishlistecom-wishlist
useCompareecom-compare
useRecentlyViewedecom-recently-viewed

The stored value holds whole product objects, not just ids, so a cart survives even if a product later disappears from the backend. The flip side is that a price change is not reflected in an old cart until the item is re-added — re-validate server-side before charging.

Coupons​

setDiscountCode checks the code against the coupons in runtime config. A percent coupon takes that percentage off the subtotal; a flat coupon subtracts its value, and a flat coupon with value: 0 is how free shipping is expressed.

const { setDiscountCode, discount, discountCode } = useCart();

setDiscountCode('SAVE10');
// discount is now 10% of the subtotal

Next​