useResults

This hook must not be used to render the results grid, the results grid must always be rendered by using the Results component.

Purpose

The useResults hook exposes data for results and result stats.

This can be useful for calculating information from the current results, such as a list of all the collections found in the results.

Usage

import React from "react";
import { useResults, ElasticDocumentType } from "@usereactify/search";

export const ExampleHookUseResults: React.FC = () => {
  const resultsHook = useResults();

  const collections = resultsHook.results
    .map((result) => {
      if (result.type === ElasticDocumentType.Product) {
        return result.collections;
      }

      return [];
    })
    .flat()
    .filter(
      (item, index, self) =>
        self.findIndex((itemNested) => itemNested?.id === item?.id) === index
    );

  return (
    <ul>
      {collections.map((collection) => (
        <li>
          <a href={`/collections/${collection?.handle}`}>{collection?.title}</a>
        </li>
      ))}
    </ul>
  );
};

Signature

(): {
  /** Equals true until first load has completed */
  loading: boolean;
  /** All of the current results */
  results: ReactivesearchResultProps["data"];
  /** Function for setting the current results */
  setResults: React.Dispatch<
    React.SetStateAction<ReactivesearchResultProps["data"]>
  >;
  /** All of the current result stats */
  resultStats?: ReactivesearchResultProps["resultStats"];
  /** Function for setting the current result stats */
  setResultStats: React.Dispatch<
    React.SetStateAction<ReactivesearchResultProps["resultStats"] | undefined>
  >;
}

Last updated