useSearch
The useSearch hook enables searching with pagination. It’s ideal for traditional searches with pagination where users navigate between pages using page numbers.
Configuration
To use the hook, you can provide the searchIndexId and the search query.
Supported parameters
The hook expects the ID of the search index and also supports several other parameters used to sort, paginate, keep previous search data, etc.
|
Parameter |
Type |
Description |
|---|---|---|
|
|
string |
The ID of the SitecoreAI search index to retrieve results from. Required |
|
|
string |
Specify a query to search the index for specific content. |
|
|
number |
Specify the page number to retrieve results from. It is 1-indexed, meaning it starts from 1, 2, 3... and so on, and defaults to 1 when empty. |
|
|
number |
Specify the number of results per page. |
|
|
|
Specify an object or array of objects containing the name and order to sort results by. |
|
|
boolean |
Specify whether to run a manual search. |
|
|
boolean |
Specify whether previous search results should be kept when performing a new search. |
Examples
The hook contains all traditional searching capabilities like sorting (single, multi-field, and nested fields), pagination, manual search execution, and keeping previous data while searching. The hook also supports TypeScript generics that lets you define the shape of your search results for type safety.
Simple search with keyphrase
A basic search requires only the searchIndexId. You can specify additional parameters as needed.
Search with a generic type
The useSearch hook supports TypeScript generics, allowing you to define the shape of your search document for type safety and better IDE support.
Search with pagination
The useSearch hook supports pagination through the page parameter. The hook automatically calculates the offset based on the page number and page size:
Search with basic sorting
The hook supports sorting results using a single sort object specifying the name and order. The following example sorts the search results by the price in the ascending order (lowest first).
Search with multi-field sorting
You can also specify multiple fields to sort. Instead of a single object, you should specify this as an array of objects. The following example sorts the search results by category in the ascending order, followed by price in ascending order, and finally by rating in the descending order.
Search with nested field sorting
Using dot notation (.), you can sort nested properties.
Search while keeping previous data
You can keep your existing search results while performing a new search by enabling the keepPreviousData parameter. This provides a better user experience when executing search queries.
Enable manual search
You can perform a manual search by setting the enabled parameter to true. This is useful when you want the user to type in a query and click a button to perform the search.