searchForProducts(query: string, page: number): Promise<TSearchProductsResponse | null>¶
The searchForProducts
is an asynchronous method that allows you to search for products based on a given query.
Input parameters¶
query¶
query
is a mandatory parameter of string
type which represents a query to which results should be returned.
page¶
page
is a mandatory parameter of number
type which represents a page number of the returned products.
Returned value¶
A returned value is has a type of Promise<TSearchProductsResponse[] | undefined>
. You can read more about TSearchProductsResponse 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 product results based on a given query.
useStorefront(async (storefront) => {
const searchApi = await storefront.getApi('SearchApi');
const products = await searchApi.searchForProducts('black shirt', 1);
});
Example¶
In this example we listen to loadMoreProducts event and load more products whenever it's emitted.
useStorefront(async (storefront) => {
const searchApi = await storefront.getApi('SearchApi');
const $exampleElement = document.querySelector('my-element');
handleLoadMoreProducts($exampleElement);
document.addEventListener('loadMoreProducts', (event) => {
if (!event.detail) return;
const { searchPhrase, page, moduleInstanceId } = event.detail;
const moreProducts = await searchApi.searchForProducts(searchPhrase, page);
console.log('more products have been loaded', moreProducts);
// Assuming this component has a method for handling more products.
// We could also write the method globally if needed.
$element.exampleHandleMoreProducts(moreProducts);
});
});