All files / store/pages/Packages Packages.tsx

100% Statements 19/19
87.5% Branches 14/16
100% Functions 4/4
100% Lines 19/19

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                    32x 17x 17x   17x 17x           17x               32x 32x   32x 32x   32x 32x           7x   25x     32x   17x           32x 32x   32x                        
import { ReactNode } from "react";
import { useQuery } from "react-query";
import { useLocation, useSearchParams } from "react-router-dom";
import { v4 as uuidv4 } from "uuid";
 
import type { Package, Store } from "../../types";
import { PackageList } from "../../components/PackageList/PackageList";
import { EmptyResultSection } from "../../components/EmptyResultSection";
 
function Packages(): ReactNode {
  const getData = async (queryString: string) => {
    const response = await fetch(`/store.json${queryString}`);
    const data: Store = await response.json();
 
    const packagesWithId = data.packages.map((item: Package) => {
      return {
        ...item,
        id: uuidv4(),
      };
    });
 
    return {
      total_items: data.total_items,
      total_pages: data.total_pages,
      packages: packagesWithId,
      categories: data.categories,
    };
  };
 
  const { search } = useLocation();
  const [searchParams] = useSearchParams();
 
  const currentPage = searchParams.get("page") || "1";
  const searchTerm = searchParams.get("q");
 
  let queryString = search;
  if (
    !search ||
    (!searchParams.get("categories") &&
      !searchTerm &&
      !searchParams.get("architecture"))
  ) {
    queryString = `?categories=featured&page=${currentPage}`;
  } else {
    queryString += `&page=${currentPage}`;
  }
 
  const { data, status, isFetching } = useQuery(
    ["data", queryString],
    () => getData(queryString),
    {
      keepPreviousData: true,
    },
  );
 
  const packagesCount = data?.packages ? data?.packages.length : 0;
  const isResultExist = status === "success" && packagesCount > 0;
 
  return isResultExist || isFetching ? (
    <PackageList data={data} isFetching={isFetching} />
  ) : (
    <EmptyResultSection
      searchTerm={searchTerm}
      data={data}
      isFetching={isFetching}
    />
  );
}
 
export default Packages;