All files / pages/admin/AddAsset/components Selector.tsx

85.71% Statements 18/21
60% Branches 3/5
80% Functions 4/5
85.71% Lines 18/21

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 69 70 71 72 73 74 75 762x 2x   2x 2x 2x                 9x 9x     9x           9x 8x 1x   1x     8x         9x 8x         9x                     17x                                         2x  
import { useState, useEffect, useRef } from "react";
import { Divider, Select, Space, message } from "antd";
import APIResponse from "../../../../types/APIResponse";
import { useQuery } from "react-query";
import { CategoryAPICaller } from "../../../../services/apis/category.api";
import AddCategoryButton from "./AddCategoryButton";
import { Category } from "@/types/Category";
 
interface SelectorProps {
  value?: string;
  onChange?: (value: string) => void;
}
 
function Selector({ value, onChange }: SelectorProps) {
  const [items, setItems] = useState<Category[]>([]);
  const dropdownRef = useRef<HTMLDivElement | null>(null);
 
  // query
  const { data, isError, error, isSuccess } = useQuery(
    "getAllCategories",
    CategoryAPICaller.getAll
  );
 
  // effect
  useEffect(() => {
    if (isError) {
      const errorResponse = (error as { response: { data: APIResponse } })
        .response.data;
      message.error(errorResponse.message);
    }
 
    Iif (isSuccess) {
      setItems(data.data.result);
    }
  }, [isError, isSuccess, data]);
 
  useEffect(() => {
    Iif (items && dropdownRef.current) {
      dropdownRef.current.scrollTop = dropdownRef.current.scrollHeight;
    }
  }, [items]);
 
  return (
    <>
      <Select
        value={value}
        onChange={onChange}
        // placeholder=""
        listItemHeight={999}
        listHeight={9999}
        // id="category"
        aria-label="category"
        dropdownRender={(menu) => (
          <>
            <div ref={dropdownRef} style={{ maxHeight: 175, overflow: "auto" }}>
              {menu}
              <Divider style={{ margin: "8px 0" }} />
            </div>
            <Space style={{ padding: "0 8px 4px" }}>
              <div className="cursor-pointer mt-1 z-10">
                <AddCategoryButton items={items} setItems={setItems} />
              </div>
            </Space>
          </>
        )}
        options={items.map((item) => ({
          label: item["name"],
          value: item["name"],
        }))}
      />
    </>
  );
}
 
export default Selector;