All files / src/components/common/Select useSearchbar.ts

46.15% Statements 12/26
0% Branches 0/9
50% Functions 4/8
44% Lines 11/25

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                  156x 447x 447x   447x                   447x   447x                 447x 89x 87x       447x                   156x                        
import { useEffect, useRef, useState } from "react";
import { SelectOptionProps } from "./types";
import debounce from "lodash.debounce";
 
type Args = {
  initialOptions?: SelectOptionProps[];
  customSearch?: (newValue: string) => void;
};
 
const useSearchbar = ({ initialOptions = [], customSearch }: Args) => {
  const [query, setQuery] = useState("");
  const [options, setOptions] = useState<SelectOptionProps[]>([]);
 
  const debouncedSearch = useRef(
    debounce((value: string) => {
      if (customSearch) {
        customSearch(value);
      } else {
        setOptions(filterArray(initialOptions, value));
      }
    }, 200),
  );
 
  const resetOptions = () => setOptions(initialOptions);
 
  const onSearch = (newValue: string) => {
    setQuery(newValue);
    if (newValue) {
      debouncedSearch.current(newValue);
    } else {
      resetOptions();
    }
  };
 
  useEffect(() => {
    return () => {
      debouncedSearch.current.cancel();
    };
  }, []);
 
  return {
    query,
    options,
    onSearch,
    resetOptions,
  };
};
 
export default useSearchbar;
 
const filterArray = (array: SelectOptionProps[], query: string) => {
  const lowerCaseQuery = query.toLowerCase();
  return array?.filter((x) => {
    if (x.label?.toString().toLowerCase().includes(lowerCaseQuery)) {
      return true;
    } else if (typeof x?.hidden === "boolean") {
      return x.hidden;
    } else {
      return false;
    }
  });
};