Blog>
Snippets

Filtering and Faceting Search Results with React Query and Algolia

Illustrate how to implement filtering and faceting in a search interface, using React Query for state management and Algolia for the search logic, enhancing user search experiences.
import { useQuery } from 'react-query';
import algoliasearch from 'algoliasearch/lite';

// Initialize Algolia search client
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
const algoliaIndex = searchClient.initIndex('your_index_name');
This code snippet initializes the Algolia search client with your application ID and search-only API key. It also specifies the index you'll be querying.
const fetchAlgoliaResults = async ({ queryKey }) => {
  const [_key, { query, facetFilters }] = queryKey;
  const { hits } = await algoliaIndex.search(query, { facetFilters });
  return hits;
};
Defines an asynchronous function to fetch search results from Algolia. It accepts a queryKey from react-query which includes the search query and any facetFilters for filtering results.
const useAlgoliaSearch = (query, facetFilters) => {
  return useQuery(['algoliaSearch', { query, facetFilters }], fetchAlgoliaResults);
};
This custom hook uses react-query's useQuery to fetch and cache search results from Algolia based on the user's search input and selected facet filters.
const SearchResults = ({ query, facetFilters }) => {
  const { data: hits, isError, isLoading } = useAlgoliaSearch(query, facetFilters);

  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error fetching results.</div>;

  return (
    <ul>
      {hits.map(hit => (
        <li key={hit.objectID}>{hit.name}</li>
      ))}
    </ul>
  );
};
A component that displays the search results. It uses the useAlgoliaSearch hook to fetch results based on the current query and selected facet filters. It handles loading and error states, and renders a list of hits.
const FacetFilter = ({ attribute, onSelectFilter }) => {
  // Example facet values could be hard-coded or fetched from Algolia
  const facets = ['Brand A', 'Brand B', 'Brand C'];

  return (
    <div>
      {facets.map(facet => (
        <button key={facet} onClick={() => onSelectFilter(`${attribute}:${facet}`)}>
          {facet}
        </button>
      ))}
    </div>
  );
};
This component renders buttons for each facet filter value. When a button is clicked, it calls onSelectFilter with the filter to apply. In a real application, facets could be fetched dynamically from Algolia.