Documentation
Feedback
Guides
Storefront Development

Storefront Development
FastStore
useSearch
The useSearch hook provides access to the search context managed by the SearchProvider component. It enables reading and modifying the search state, such as sorting criteria, selected facets, and pagination. Use this hook to build interactive search features like sorting dropdowns, facet filters, and pagination controls.

Import


_10
import { useSearch } from '@faststore/sdk'

Usage

The following example shows how to implement a sorting dropdown using useSearch:

_36
import { useSearch } from '@faststore/sdk'
_36
_36
// Example: A sort dropdown to change the search sorting criteria
_36
_36
const keyMap = {
_36
price_desc: 'Price, descending',
_36
price_asc: 'Price, ascending',
_36
orders_desc: 'Top sales',
_36
name_asc: 'Name, A-Z',
_36
name_desc: 'Name, Z-A',
_36
release_desc: 'Release date',
_36
discount_desc: 'Discount',
_36
score_desc: 'Relevance',
_36
}
_36
_36
const keys = Object.keys(keyMap)
_36
_36
function Component () {
_36
const {
_36
setSort,
_36
state: { sort },
_36
} = useSearch()
_36
_36
return (
_36
<select
_36
onChange={(e) => setSort(keys[e.target.selectedIndex])}
_36
value={sort}
_36
>
_36
{keys.map((key) => (
_36
<option key={key} value={key}>
_36
{keyMap[key]}
_36
</option>
_36
))}
_36
</select>
_36
)
_36
}

useSearch: Accesses the search context to read and update the search state. keyMap: Maps sorting keys to user-friendly labels. setSort: Updates the sorting criteria. sort: Contains the current sorting criteria from the search state.

API reference

The useSearch hook returns an object with the following properties and functions:
Variable nameData typeDescription
itemsPerPagenumberNumber of items displayed per page.
stateSearchStateContains the current state of the search, including selected facets, sorting criteria, and pagination.
setSort(sort: SearchSort) => voidUpdates the sorting criteria of the search results.
setTerm(term: string / null) => voidUpdates the full-text search term.
setPage(page: number) => voidUpdates the current page in the search pagination.
removeFacet(facet: Facet) => voidRemoves a specific facet from the search state.
toggleFacet(facet: Facet) => voidToggles a specific facet in the search state. If the facet is already selected, it will be removed; otherwise, it will be added.
toggleFacets(facets: Facet[]) => voidToggles multiple facets in the search state.
addPrevPage() => voidPrepends a page of results to the current list (used in infinite scroll).
addNextPage() => voidAppends a page of results to the current list (used in infinite scroll).
Contributors
1
Photo of the contributor
Was this helpful?
Yes
No
Suggest Edits (GitHub)
Contributors
1
Photo of the contributor
On this page