useSearch
The useSearch hook is a specialized wrapper around useFetch used for executing flexible search requests. It is the primary hook for products, categories, or custom entities and handles cache key generation and state management. It works on the client as well as on the server.
import { useSearch } from '@archibald/search';
const { data: results, isLoading, error } = useSearch(key, searchOptions, fetchOptions);
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| key | FetchKey | ✔️ | The key to uniquely identify the search in the cache. |
| searchOptions | SearchRequestOptions | ✔️ | Options for the search request. |
| fetchOptions | FetchMinOptions | Standard options for the useFetch hook. |
key
The cache key. If the key changes, the search will be re-executed. See FetchKey for more information.
searchOptions
- Type:
SearchRequestOptions
| Property | Type | Description |
|---|---|---|
| categoryId | string | Optional category ID to search within. |
| search | string | The search term or query string. |
| pageSize | number | Number of results per page. |
| entity | 'products' | string | The type of entity to search for. |
fetchOptions
Standard data fetching options. See FetchOptions for more information.
Return value
- Type:
FetchResult<SearchResponse>
| Property | Type | Description |
|---|---|---|
| data | SearchResponse | null | The search results, including products, facets, and pagination info. |
| error | DefaultResponseError | null | Any error that occurred during the search. |
| isLoading | boolean | True if the search is in progress. |
| isDone | boolean | True if the search has finished. |
| refetch | Function | Triggers a manual refresh of the search. |
Example
import { useSearch } from '@archibald/search';
function AdvancedSearch({ query, catId, currentPage }) {
const searchOptions = {
search: query,
categoryId: catId,
pageSize: 24,
currentPage
};
const { data, isLoading } = useSearch(['adv-search', query, catId, currentPage], searchOptions);
if (isLoading) return <SearchSkeleton />;
return (
<div>
<FacetList facets={data.facets} />
<ProductGrid products={data.products} />
<Pagination data={data.pagination} />
</div>
);
}