All files / components/Nav MenuItemSearch.jsx

100% Statements 17/17
100% Branches 0/0
100% Functions 5/5
100% Lines 17/17

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                    277x 277x   277x   277x 4x 4x 4x     3x   1x 1x 1x   4x           277x 1x     277x                     8x           8x                      
import { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router";
import { AsyncTypeahead } from "react-bootstrap-typeahead";
import { toast } from "react-toastify";
import { diningCommonsName } from "main/utils/diningCommonsNames";
 
import "react-bootstrap-typeahead/css/Typeahead.css";
 
export default function MenuItemSearch() {
  const navigate = useNavigate();
  const [isLoading, setIsLoading] = useState(false);
  // Stryker disable next-line ArrayDeclaration : the menu is hidden until a search returns, so initial options are never shown
  const [options, setOptions] = useState([]);
 
  const handleSearch = async (query) => {
    setIsLoading(true);
    try {
      const response = await axios.get("/api/diningcommons/menuitem/search", {
        params: { query },
      });
      setOptions(response.data);
    } catch (e) {
      console.error("Error searching menu items", e);
      toast("Error searching menu items");
      setOptions([]);
    } finally {
      setIsLoading(false);
    }
  };
 
  // `selected` is held at [] (below), so onChange only fires when the user
  // picks an option, and always with exactly that one option.
  const handleChange = (selected) => {
    navigate(`/reviews/${selected[0].id}`);
  };
 
  return (
    <AsyncTypeahead
      id="menu-item-search"
      className="me-3"
      inputProps={{ "data-testid": "MenuItemSearch-input" }}
      isLoading={isLoading}
      minLength={2}
      onSearch={handleSearch}
      onChange={handleChange}
      options={options}
      // The backend already filters by name, so show every result it returns.
      filterBy={() => true}
      labelKey="name"
      placeholder="Search menu items..."
      emptyLabel="No matching menu items."
      selected={[]}
      renderMenuItemChildren={(item) => (
        <div data-testid={`MenuItemSearch-option-${item.id}`}>
          <div>{item.name}</div>
          <small className="text-muted">
            {diningCommonsName(item.diningCommonsCode)} · {item.mealCode} ·{" "}
            {item.station}
          </small>
        </div>
      )}
    />
  );
}