useProduct
Keep a product object live: it updates its price and stock when the customer picks options, and can be reloaded.
Use useProduct on a product page, where the price and stock must follow the options the customer selects. Give it the product your route loader returned.
Example
import { useProduct } from '@salla.sa/twilight-theme-engine/hooks/useProduct';
import { useMoney } from '@salla.sa/twilight-theme-engine/hooks/useMoney';
import type { Product } from '@salla.sa/twilight-theme-engine/types';
export function ProductPrice({ initial }: { initial: Product }) {
const { product } = useProduct(initial);
const { format } = useMoney();
return (
<p>{product.is_out_of_stock ? 'Out of stock' : format(product.price)}</p>
);
}API
function useProduct(
initialProduct: Product,
options?: UseProductOptions
): UseProductResult;| Prop | Type | Description |
|---|---|---|
initialProduct | Product | The product from your route loader. Required. |
options.isPreview? | boolean | Pass true while the product is only a list-card stand-in. When it turns false, the hook re-seeds from the full product. |
Returns:
| Prop | Type | Description |
|---|---|---|
product | Product | The current product. |
reload | () => Promise<void> | Fetches the product again from the Salla SDK (with images and category) and replaces the state. |
Gotchas
- Live updates happen in the browser only. On the server you get
initialProductunchanged. - The hook listens to the SDK events
product:options.updated(reloads the product),product::price.updated(updatesprice,regular_price,is_on_saleandweight, plusskuandbarcodewhen the payload has them, setssale_priceto the new price when on sale, clearsstarting_price, and setsis_out_of_stocktofalse) andproduct::price.updated.failed(setsis_out_of_stocktotrue). - State re-seeds when
initialProduct.idchanges, not when the object changes. A new object for the same product does not reset the customer's choices. reloadignores errors and does nothing when the SDK is missing. It does not add anything to the cart.
Next
- Product data: every field of the product, with example values.
useMoneyformats the price you show.- Loading data explains where
initialProductcomes from. - Salla SDK and events