useProduct
The useProduct hook is a specialized wrapper around useFetch used to fetch a single product by its code. It handles product-specific logic and caching, automatically generating a cache key based on the productCode. It works on the client as well as on the server.
import { useProduct } from '@archibald/product';
const { data: product, isLoading, error } = useProduct(productCode, productOptions, fetchOptions);
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| productCode | string | ✔️ | The code of the product to fetch. |
| productOptions | ProductRequestOptions | Options for the product request. | |
| fetchOptions | FetchMinOptions | Standard options for the useFetch hook. |
productCode
The unique identifier of the product.
productOptions
- Type:
ProductRequestOptions
| Name | Type | Description |
|---|---|---|
| fields | string | Defines the depth of the returned product data (e.g., 'BASIC', 'DEFAULT', 'FULL'). |
fetchOptions
Standard data fetching options. See FetchOptions for more information.
Return value
- Type:
FetchResult<Product>
| Property | Type | Description |
|---|---|---|
| data | Product | null | The product data retrieved from the backend. |
| error | DefaultResponseError | null | Any error that occurred during the fetch. |
| isLoading | boolean | True if the request is currently in progress. |
| isDone | boolean | True if the request has finished. |
| isError | boolean | True if the request resulted in an error. |
| isPrefetched | boolean | True if the data was prefetched on the server. |
| isStale | boolean | True if the data was retrieved from cache. |
| refetch | Function | A function to manually trigger a refresh. |
| request | DataRequest | The underlying DataRequest instance. |
Example
import { useProduct } from '@archibald/product';
function ProductDetail({ productCode }) {
const { data: product, isLoading, error } = useProduct(productCode, { fields: 'FULL' });
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
if (!product) return <div>Product not found</div>;
return (
<div>
<h1>{product.name}</h1>
<p>{product.summary}</p>
<span>Price: {product.price?.formattedValue}</span>
</div>
);
}