All files / src/views/Search useSearchParam.ts

29.03% Statements 9/31
0% Branches 0/12
0% Functions 0/12
30% Lines 9/30

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 76 77                1x                           1x             1x                 1x                 1x                 1x         1x         1x           1x        
import { useMemo } from "react";
import { parseQueryArray, toNum } from "./util";
import { CatalogSearchSort } from "../../api/catalog-search/constants";
import { CDKType } from "../../constants/constructs";
import { Language } from "../../constants/languages";
import { QUERY_PARAMS } from "../../constants/url";
import { useQueryParams } from "../../hooks/useQueryParams";
 
const useSearchParam = <T = string | null>(
  key: string,
  transform?: (param: string | null) => T
): T => {
  const queryParams = useQueryParams();
  const qp = queryParams.get(key);
 
  return useMemo(
    () => (transform ? transform(qp) : (qp as unknown as T)),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [qp]
  );
};
 
export const useCdkType = () => {
  const cdkType: CDKType | undefined =
    useSearchParam(QUERY_PARAMS.CDK_TYPE) ?? undefined;
 
  return cdkType;
};
 
export const useCdkMajor = () => {
  const cdkMajor: number | undefined = useSearchParam(
    QUERY_PARAMS.CDK_MAJOR,
    (p) => (p ? toNum(p) : undefined)
  );
 
  return cdkMajor;
};
 
export const useKeywords = () => {
  const keywords: string[] = useSearchParam(
    QUERY_PARAMS.KEYWORDS,
    parseQueryArray
  );
 
  return keywords;
};
 
export const useLanguages = () => {
  const languages: Language[] = useSearchParam(
    QUERY_PARAMS.LANGUAGES,
    parseQueryArray
  ) as Language[];
 
  return languages;
};
 
export const useOffset = () => {
  const offset = useSearchParam(QUERY_PARAMS.OFFSET, (o) => toNum(o ?? ""));
  return offset;
};
 
export const useSearchQuery = () => {
  const query: string = useSearchParam(QUERY_PARAMS.SEARCH_QUERY) ?? "";
  return query;
};
 
export const useSort = () => {
  const sort: CatalogSearchSort | undefined =
    useSearchParam(QUERY_PARAMS.SORT) ?? undefined;
  return sort;
};
 
export const useTags = () => {
  const tags: string[] = useSearchParam(QUERY_PARAMS.TAGS, parseQueryArray);
  return tags;
};