Search Results
Learn how to integrate Fast Simon's search functionality into your Hydrogen app by adding the getSearchResults
function to the root loader.
Step 1: Add getSearchResults
to the Root Loader
- Navigate to the file:
routes/search.tsx
. - Invoke
getSearchResults
:- Use it in your root loader function in the same file.
- Pass parameters such as the search query, page number, sort by, and narrow filters.
- Pass the Results:
- Forward the fetched data to the search component.
export async function loader({request, params, context}) {
const url = new URL(request.url);
const searchPromise = regularSearch({request, context});
searchPromise.catch((error: Error) => {
console.error(error);
return {term: '', result: null, error: error.message};
});
const data = await searchPromise;
const facets = {facets: data.result.getFacetsOnly ? data.result.getFacetsOnly() : data.result.facets};
return defer({...data, ...facets});
}
Step 2: Define the Search Logic
async function regularSearch({
request,
context,
}: Pick<
LoaderFunctionArgs,
'request' | 'context'
>): Promise<RegularSearchReturn> {
const {fastSimon} = context;
const url = new URL(request.url);
const term = String(url.searchParams.get('q') || '');
const page = Number(url.searchParams.get('page') || 1);
const sortBy = url.searchParams.get('sort');
const narrowString = url.searchParams.get('filters');
const narrow = narrowString ? Narrow.toServerNarrow(Narrow.parseNarrow(narrowString || '')) : []
const fastSimonSearchResults = await fastSimon.getSearchResults({
props: {
page: page,
narrow: narrow,
facetsRequired: 1,
query: term,
productsPerPage: 20,
sortBy: sortBy
}
});
if (!fastSimonSearchResults) {
throw new Error('No search data returned from FastSimon API');
}
const transformed = transformToShopifyStructure(fastSimonSearchResults.items);
const facets = fastSimonSearchResults.getFacetsOnly ? fastSimonSearchResults.getFacetsOnly() : {};
return {type: 'regular', term, error: undefined, result: {total: fastSimonSearchResults.total_results, ...fastSimonSearchResults, ...facets, items: transformed}};
}
Key Concepts
Translating Fast Simon Results
- Use
transformToShopifyStructure
to convert Fast Simon search results into Shopify GraphQL-compatible data - This step allows you to leverage Shopify’s template components but is optional if you use custom components.
Handling Facets
Fast Simon facets can be optimized in two scenarios:
- Facets Ready in the Collection Response:
- Assign the facets directly and pass them with the rest of the data.
- Facets Not Ready:
- Use the getFacetsOnly callback in the collection response to fetch facets asynchronously.
- Pass the resulting Promise down to the stream.
Additional Notes
- For detailed examples of rendering streamed facets, refer to the Filters component in the sample site.
- Ensure the search component can handle the transformed data appropriately.