All files / components/Nav MenuItemSearchContainer.jsx

100% Statements 30/30
100% Branches 8/8
100% Functions 7/7
100% Lines 29/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68          26x       614x   614x 614x 614x 614x   614x 162x   162x 143x 143x 143x 143x     19x   19x 19x   19x           14x 13x 13x       5x 3x 3x 3x       19x     614x         22x 22x   1x            
import { useEffect, useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router";
import MenuItemSearch from "main/components/Nav/MenuItemSearch";
 
const SEARCH_URL = "/api/diningcommons/menuitems/search";
 
/** Connects the menu item typeahead to the backend and review pages. */
export default function MenuItemSearchContainer() {
  const navigate = useNavigate();
 
  const [query, setQuery] = useState("");
  const [results, setResults] = useState([]);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
 
  useEffect(() => {
    const search = query.trim();
 
    if (search.length < 2) {
      setResults([]);
      setIsLoading(false);
      setError(null);
      return;
    }
 
    const controller = new AbortController();
 
    setIsLoading(true);
    setError(null);
 
    axios
      .get(SEARCH_URL, {
        params: { q: search },
        signal: controller.signal,
      })
      .then(({ data }) => {
        if (!controller.signal.aborted) {
          setResults(data);
          setIsLoading(false);
        }
      })
      .catch(() => {
        if (!controller.signal.aborted) {
          setResults([]);
          setError("Unable to search menu items. Please try again.");
          setIsLoading(false);
        }
      });
 
    return () => controller.abort();
  }, [query]);
 
  return (
    <MenuItemSearch
      results={results}
      query={query.trim().length >= 2 ? query : ""}
      onQueryChange={(value) => {
        setQuery(value);
        setResults([]);
      }}
      onSelect={(item) => navigate(`/reviews/${item.id}`)}
      isLoading={isLoading}
      error={error}
    />
  );
}