useProducts
The useProducts hook is a specialized wrapper around useFetch used to fetch multiple products by their codes. It automatically handles cache key generation and state management.
warning
This hook should be used with caution. For general product listing and searching, please use the Search module instead. This hook is intended for specific use cases like product aggregators or custom project requirements.
import { useProducts } from '@archibald/product';
const { data: products, isLoading, error } = useProducts(productCodes, productOptions, fetchOptions);
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| productCodes | string[] | ✔️ | An array of product codes to fetch. |
| productOptions | ProductRequestOptions | Options for the product request. | |
| fetchOptions | FetchMinOptions | Standard options for the useFetch hook. |
productCodes
An array of strings, where each string is a unique product code.
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 list of 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. |
| refetch | Function | A function to manually trigger a refresh. |
| request | DataRequest | The underlying DataRequest instance. |
Example
import { useProducts } from '@archibald/product';
function RelatedProducts({ codes }) {
const { data: products, isLoading, error } = useProducts(codes, { fields: 'BASIC' });
if (isLoading) return <div>Loading related products...</div>;
if (error) return <div>Failed to load related products.</div>;
return (
<ul>
{products?.map(product => (
<li key={product.code}>{product.name}</li>
))}
</ul>
);
}