Skip to main content

Predictive search provider

The PredictiveSearchProvider component runs predictive search for the React or Vue components inside the provider. Use the provider with the predictive search hooks to build a search form, show results, and clear results.

Import PredictiveSearchProvider, usePredictiveSearch, usePredictiveSearchActions, and usePredictiveSearchForm from @shopify/hydrogen/react or @shopify/hydrogen/vue.

Call the hooks and composables inside the provider.


Store options, the search page path, and the content that uses the predictive search hooks.

Changing a store option clears the current term and results. The provider compares types and searchableFields by value, which lets you pass new arrays on each render.

Anchor to children
children
ReactNode

Content that uses the predictive search hooks.

Anchor to debounceInMs
debounceInMs
number

Milliseconds to wait after the latest term change before searching.

Defaults to 150. Pass 0 to search right away. Negative and non-finite values use the default.

Anchor to fetch
fetch
{ (input: RequestInfo | URL, init?: RequestInit): Promise<Response>; (input: string | Request | URL, init?: RequestInit): Promise<Response>; }

Function that sends search requests. Defaults to the global fetch. Pass a function for tests or for runtimes without a global fetch.

Anchor to limit
limit
number

Maximum number of results, from 1 to 10. The server handlers clamp other values to that range.

Anchor to limitScope
limitScope
PredictiveSearchLimitScope

Whether the limit applies to each result type or to all result types combined.

Anchor to minTermLength
minTermLength
number

Number of characters a term needs, after trimming, before the store searches.

Defaults to 1. Negative and non-finite values use the default.

Anchor to predictiveSearchEndpoint
predictiveSearchEndpoint
string

Route that returns predictive search results as JSON, in the shape that createPredictiveSearchServerHandlers returns.

Defaults to /api/predictive-search.

Anchor to searchableFields
searchableFields
SearchableField[]

Fields to search for page, article, and collection results.

Anchor to searchAction
searchAction
string

Search page path that forms from usePredictiveSearchForm submit to. Defaults to /search.

Anchor to types
types
PredictiveSearchType[]

Result types to include.

Anchor to unavailableProducts
unavailableProducts
SearchUnavailableProductsType

Whether results hide unavailable products, show them, or list them last.

Examples

React

import { PredictiveSearchProvider } from "@shopify/hydrogen/react";
import type { ReactNode } from "react";

export function SearchAside({ children }: { children: ReactNode }) {
return (
<PredictiveSearchProvider limit={5} types={["PRODUCT"]} searchAction="/search">
{children}
</PredictiveSearchProvider>
);
}

Returns the search term, status, results, and error, and re-renders the component on each change.

Pass a selector to read one value, such as the status, and re-render only when that value changes. The hook compares selected values by reference unless you pass an equality function. The hook throws an error outside a PredictiveSearchProvider.

Anchor to selector
selector
(state: ) => S

Function that picks the value to return from the search state.

Anchor to isEqual
isEqual
(a: S, b: S) => boolean

Function that compares two selected values. Return true to skip the re-render.

S =

The search state, or the value that your selector picks.

Examples

React

import { usePredictiveSearch } from "@shopify/hydrogen/react";

export function PredictiveResults() {
const { status, result, error } = usePredictiveSearch();

if (status === "loading") return <p>Loading...</p>;
if (status === "error") return <p role="alert">{error}</p>;
if (!result.total) return null;

return (
<ul>
{result.items.products.map((product) => (
<li key={product.id}>{product.title}</li>
))}
</ul>
);
}

Anchor to usePredictiveSearchActions
usePredictiveSearchActions()

Returns methods that search for a term and clear the results of the provider's predictive search. Use the hook in components that start searches without reading results.

The methods keep the same identity across re-renders and keep working after a store option changes. The hook throws an error outside a PredictiveSearchProvider.

Methods that search for a term and clear the results.

Examples

React

import { usePredictiveSearchActions } from "@shopify/hydrogen/react";

export function CloseSearchButton({ onClose }: { onClose: () => void }) {
const { clear } = usePredictiveSearchActions();

function closeSearch() {
clear();
onClose();
}

return (
<button type="button" onClick={closeSearch}>
Close
</button>
);
}

Anchor to usePredictiveSearchForm
usePredictiveSearchForm()

Returns functions that connect a search form and its search input to the provider's predictive search. The form submits to the search page without JavaScript, and the search input searches as the customer types.

Spread formProps() on the form and register("query") on the input. In the onSubmit and onChange callbacks, call event.preventDefault() to skip the automatic submission or search. The hook throws an error outside a PredictiveSearchProvider.

Functions that return the search form attributes and the search input attributes.

Examples

React

import { usePredictiveSearchForm } from "@shopify/hydrogen/react";

export function PredictiveSearchForm() {
const { formProps, register } = usePredictiveSearchForm();

return (
<form {...formProps()}>
<input {...register("query", { placeholder: "Search", "aria-label": "Search products" })} />
<button type="submit">Search</button>
</form>
);
}

  • The Vue provider renders its default slot.
  • The Vue usePredictiveSearch composable returns a read-only ref. Read .value in script code.
  • The Vue usePredictiveSearchForm composable searches on each input event. Pass an onInput callback to register(). The form callbacks receive native DOM events.

Was this page helpful?