useProducts
Overview
The useProducts hook is designed to manage and retrieve the list of products from the current search results within an e-commerce platform. It provides essential details like the list of products, the starting index of the products, and the total number of products available based on the search query.
Usage
import { useProducts } from "@unbxd-ui/react-search-hooks";
⚠️
Note:
The useProducts hook must be used within the wrapper (in CSR, SSR and Custom Hooks approaches) to ensure that the respective component(s) and the search functionality work properly.
Code Example
import { useProducts, useProductView } from "@unbxd-ui/react-search-hooks";
const ProductListComponent = () => {
const { productType, products, start, numberOfProducts} = useProducts();
const { view } = useProductView();
const renderSummary = (productType) => {
if(productType === "SEARCH") {
return <p>Showing {products.length} products starting from index {start + 1} out of {numberOfProducts} total products.</p>
} else {
return <p>Total products in this category: {numberOfProducts}</p>
}
}
return (
<div className={`product-list ${view == "grid" ? "grid": "list"}`}>
{renderSummary(productType)}
<ul>
{products.map((product, index) => (
<li key={index}>
<h2>{product.name}</h2>
<p>Price: ${product.price}</p>
<img src={product.imageUrl} alt={product.name} />
</li>
))}
</ul>
</div>
);
};
Hook API
Return Values
- A boolean value which indicates if an API call is being made. It is true when an API call is made and false otherwise. It can be used to hide and show the
LoaderComponent
.
- A string value indicating the type of product listing. It can be either
SEARCH
orCATEGORY
, based on whether the current results are from a search or a category browse.
- An array of products retrieved from the search results. Each product is an object containing various attributes relevant to the product (e.g., name, price, image).
Format Example:
products = [
{
"uniqueId": "product_123",
"title": "Wireless Bluetooth Headphones",
"price": "$99.99",
"sellingPrice": 99.99,
"brand": "TechBrand",
"imageUrl": "https://example.com/images/headphones.jpg",
"productUrl": "/products/wireless-bluetooth-headphones",
"availability": "In Stock",
"rating": 4.5,
"reviewCount": 128,
"category": "Electronics > Audio > Headphones",
"color": "Black",
"size": "One Size",
"description": "High-quality wireless headphones with noise cancellation",
"sku": "WBH-001",
"discount": "20% off"
}
]
- The index of the first product in the current set of products. This is useful for understanding the position of the product set within the total product range.
- The total number of products available based on the current search query.