search(suggestion: string, query?: string): Promise<TSearchResponse | null>¶
The search
is an asynchronous method that allows you to search for all items (products, producers, categories) based on a given query.
Input parameters¶
suggestion¶
suggestion
is a mandatory parameter of string
type which represents a suggestion query to which results should be returned.
query¶
query
is an optional parameter of string
type which represents an original query to which results should be returned.
Returned value¶
A returned value is has a type of Promise<TSearchResponse[] | undefined>
. You can read more about TSearchResponse here.
Event Bus events¶
This API method dispatches the following events with the Event Bus:
- FlashMessengerApi.addFlashMessages - when handling messages that come from a server
Example¶
In this example we make a SearchApi
call to get search results based on a given query and suggestion.
useStorefront(async (storefront) => {
const searchApi = await storefront.getApi('SearchApi');
const $searchElement = document.querySelector('input[type="search"]');
$searchElement.addEventListener('keydown', (ev) => {
if (ev.key.length !== 1) return;
const searchPhrase = ev.target.value;
const suggestions = await searchApi.getSuggestions(searchPhrase);
const searchResultsWithSuggestions = await searchApi.search(suggestions[0], searchPhrase);
console.log('search results with suggestions', searchResultsWithSuggestions);
});
});