All files / components/Nav MenuItemSearch.jsx

100% Statements 27/27
100% Branches 4/4
100% Functions 5/5
100% Lines 27/27

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                284x 284x 284x 284x 284x   284x 10x 10x 10x   10x 10x 10x 10x     9x   1x       10x 1x   9x 1x   9x 9x     284x 3x 3x     284x                     42x   42x                
import { useRef, useState } from "react";
import axios from "axios";
import { toast } from "react-toastify";
import { useNavigate } from "react-router";
import { AsyncTypeahead } from "react-bootstrap-typeahead";
import "react-bootstrap-typeahead/css/Typeahead.css";
 
export default function MenuItemSearch() {
  const navigate = useNavigate();
  const typeaheadRef = useRef();
  const latestQuery = useRef();
  const [isLoading, setIsLoading] = useState(false);
  const [options, setOptions] = useState([]);
 
  const handleSearch = async (query) => {
    const trimmedQuery = query.trim();
    latestQuery.current = trimmedQuery;
    setIsLoading(true);
 
    let results = [];
    let failed = false;
    try {
      const response = await axios.get("/api/diningcommons/menuitem/search", {
        params: { query: trimmedQuery },
      });
      results = response.data;
    } catch {
      failed = true;
    }
 
    // A newer search has started since this one; its response is the one to show.
    if (latestQuery.current !== trimmedQuery) {
      return;
    }
    if (failed) {
      toast("Error searching for menu items");
    }
    setOptions(results);
    setIsLoading(false);
  };
 
  const handleChange = (selected) => {
    navigate(`/reviews/${selected[0].id}`);
    typeaheadRef.current.clear();
  };
 
  return (
    <AsyncTypeahead
      ref={typeaheadRef}
      id="menu-item-search"
      labelKey="name"
      placeholder="Search menu items"
      inputProps={{ "aria-label": "Search menu items" }}
      isLoading={isLoading}
      options={options}
      onSearch={handleSearch}
      onChange={handleChange}
      filterBy={() => true}
      renderMenuItemChildren={(option) => (
        <>
          <span>{option.name}</span>
          <small className="ms-2 text-muted">{option.diningCommonsCode}</small>
        </>
      )}
    />
  );
}