useSearch
Purpose
The useSearch hook exposes methods and data for updating and submitting search terms, internally it is used by the Search component.
Usage
The searchTerm
field is the current search term value.
The setSearchTerm
method is used to change the current search term value.
The submitSearchTerm
method is used to navigate to the search page, if there are redirects configured for the current search term they will be followed.
The submitSearchQuery
method is used to query products directly using the OpenSearch Query DSL, this method is detached from the rest of the search experience.
The showInstantSearchResults
is used to determine if instant search results should be displayed, e.g. you should show or hide the instant search experience based on this value.
The setShowInstantSearchResults
method is used to change the showInstantSearchResults
field value.
The searchRedirect
field will contain a Redirect if the current search term matches a redirect.
import React from "react";
import { useSearch } from "@usereactify/search";
export const ExampleHookUseSearch: React.FC = () => {
const searchHook = useSearch();
const handleFormSubmit = React.useCallback((event: React.FormEvent<HTMLFormElement>) => {
searchHook.submitSearchTerm();
}, [searchHook.submitSearchTerm]);
const handleInputChange = React.useCallback((event: React.ChangeEvent<HTMLInputElement>) => {
searchHook.setSearchTerm(event.target.value);
}, [searchHook.setSearchTerm]);
return (
<form
onSubmit={handleFormSubmit}
>
<input
type="text"
value={searchHook.searchTerm}
onChange={handleInputChange}
/>
</form>
);
};
Signature
(): {
/** The current search term */
searchTerm: string;
/** Function for changing the current search term */
setSearchTerm: (searchTerm?: string) => void;
/** Function for navigating to the search page, includes logic for redirects */
submitSearchTerm: (searchTerm?: string) => void;
/** Function for retrieving search results for an opensearch query */
submitSearchQuery: (searchBody: any, searchHeaders: Record<string, string>) => Promise<{
results: Array<Product>;
resultStats: {
time: number;
numberOfResults: number;
displayedResults: number;
};
}>;
/** Used to determine if instant search results should be displayed */
showInstantSearchResults: boolean;
/** Used to manually set the "showInstantSearchResults" value */
setShowInstantSearchResults: React.Dispatch<React.SetStateAction<boolean>>;
/** Contains any matching redirect for the current search term */
searchRedirect: {
id: string;
url: string;
query: string;
} | undefined;
};
Last updated
Was this helpful?