Skip to main content

Autocomplete

Learn how to integrate Fast Simon's autocomplete functionality into your Hydrogen app by adding the getAutocompleteResults function to your root loader.


Step 1: Add getFastSimonAutocompleteResults to Your Root Loader

  1. Navigate to the file: routes/search.tsx.
  2. Invoke getAutocompleteResults:
    • Use it in your root loader function.
    • Pass the search query as a parameter.
  3. Pass the Results:
    • Forward the fetched autocomplete data to the predictive search component.

async function getFastSimonAutocompleteResults({request, context}: LoaderFunctionArgs) {
const {fastSimon} = context;
const url = new URL(request.url);
const term = String(url.searchParams.get('q') || '').trim();

return await fastSimon.getAutocompleteResults({
props: {
query: term
}
});
}
async function predictiveSearch({
request,
context,
}: Pick<
ActionFunctionArgs,
'request' | 'context'
>): Promise<PredictiveSearchReturn> {
const url = new URL(request.url);
const term = String(url.searchParams.get('q') || '').trim();

const type = 'predictive';

if (!term) return {type, term, result: getEmptyPredictiveSearchResult()};

const {items} = await getFastSimonAutocompleteResults({request, context});

if (!items) {
throw new Error('No Autocomplete data returned from Fast Simon API');
}

const total = Object.values(items).reduce(
(acc, item) => acc + item.length,
0,
);

return {type, term, result: {items, total}};
}

Step 3: Combine Predictive and Regular Search in the Loader

export async function loader({request, context}: LoaderFunctionArgs) {
const url = new URL(request.url);
const isPredictive = url.searchParams.has('predictive');
const searchPromise = isPredictive
? predictiveSearch({request, context})
: regularSearch({request, context});

searchPromise.catch((error: Error) => {
console.error(error);
return {term: '', result: null, error: error.message};
});
const data = await searchPromise;

if(data?.type === 'regular') {
const facets = {facets: data.result.getFacetsOnly ? data.result.getFacetsOnly() : data.result.facets};
const dashboardConfig = {dashboardConfig: context.fastSimon.getDashboardConfig({cacheStrategy: CacheLong()})};
return defer({...data, ...facets, ...dashboardConfig});
}
return json(data);
}

Key Concepts

  • The loader combines regular search and autocomplete in a single function, similar to Shopify's original template.
  • It differentiates between predictive and regular searches based on the presence of the predictive query parameter.

Error Handling

  • Catches and logs errors during the search process.
  • Ensures the app gracefully handles cases where no results are returned.

Additional Notes

  • Use the predictive search functionality to enhance user experience with real-time autocomplete suggestions.
  • Customize the search and autocomplete integration further based on your app's design requirements.