useSearch

Purpose

The useSearch hook exposes methods and data for updating and submitting search terms, internally it is used by the Search component.

Usage

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<Array<Product>>;
  /** 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