Skip to main content

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

NameTypeRequiredDescription
keyFetchKey✔️The key to uniquely identify the search in the cache.
searchOptionsSearchRequestOptions✔️Options for the search request.
fetchOptionsFetchMinOptionsStandard 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
PropertyTypeDescription
categoryIdstringOptional category ID to search within.
searchstringThe search term or query string.
pageSizenumberNumber of results per page.
entity'products' | stringThe type of entity to search for.

fetchOptions

Standard data fetching options. See FetchOptions for more information.

Return value

  • Type: FetchResult<SearchResponse>
PropertyTypeDescription
dataSearchResponse | nullThe search results, including products, facets, and pagination info.
errorDefaultResponseError | nullAny error that occurred during the search.
isLoadingbooleanTrue if the search is in progress.
isDonebooleanTrue if the search has finished.
refetchFunctionTriggers 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>
);
}