React hook for fetching a WooCommerce product and optional variation by database ID
A client-side React hook that fetches a WooCommerce product by its database ID and optionally fetches a specific product variation. Used by components that need to load product data on the client after initial render.
Source: hooks/useFetchProduct/useFetchProduct.ts
import { useFetchProduct } from '@/hooks/useFetchProduct'; function ProductDetails({ productId, variationId }: { productId: number; variationId?: number }) { const { product, variation } = useFetchProduct(productId, variationId); if (!product) return <div>Loading...</div>; return ( <div> <h1>{product.name}</h1> <p>{variation?.name || product.name}</p> </div> ); }
| Parameter | Type | Required | Description |
|---|---|---|---|
productId | number | Yes | The WooCommerce database ID of the product |
variationId | number | No | The database ID of a specific variation to fetch |
| Property | Type | Description |
|---|---|---|
product | Product | undefined | The fetched product, or undefined while loading |
variation | ProductVariation | undefined | The fetched variation, or undefined if not requested or still loading |
The Product type is a union of ProductInterface, InventoriedProduct, ProductWithVariations, and ProductWithPricing, giving access to fields like name, price, stockStatus, variations, and more.
On mount - Fetches the product from /api/product/{productId} with force-cache and a 1-day revalidation period.
When variationId is provided - Also fetches the variation from /api/product/{productId}/{variationId} with the same caching strategy.
When productId changes - Re-fetches the product data.
When variationId changes - Re-fetches only the variation data.
| Route | Method | Description |
|---|---|---|
/api/product/{id} | GET | Returns a single product by database ID |
/api/product/{id}/{variationId} | GET | Returns a product variation by database ID |
The generated spec file (useFetchProduct.spec.ts) mocks apiCall and verifies:
product and variation are undefined initiallyvariationId is providedvariationId is omitted