Skip to main content

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

NameTypeRequiredDescription
productCodestring✔️The code of the product to fetch.
productOptionsProductRequestOptionsOptions for the product request.
fetchOptionsFetchMinOptionsStandard options for the useFetch hook.

productCode

The unique identifier of the product.

productOptions

  • Type: ProductRequestOptions
NameTypeDescription
fieldsstringDefines 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>
PropertyTypeDescription
dataProduct | nullThe product data retrieved from the backend.
errorDefaultResponseError | nullAny error that occurred during the fetch.
isLoadingbooleanTrue if the request is currently in progress.
isDonebooleanTrue if the request has finished.
isErrorbooleanTrue if the request resulted in an error.
isPrefetchedbooleanTrue if the data was prefetched on the server.
isStalebooleanTrue if the data was retrieved from cache.
refetchFunctionA function to manually trigger a refresh.
requestDataRequestThe 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>
);
}