All files / react-app/src/api useGetCounties.ts

78.94% Statements 15/19
80% Branches 4/5
75% Functions 9/12
81.25% Lines 13/16

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            72x 152x     39x     39x                   72x 152x   152x   152x   53x 3204x 108x         152x   152x              
import { useQuery } from "@tanstack/react-query";
import { useGetUser } from "./useGetUser";
import { getUserStateCodes } from "@/utils";
import { FULL_CENSUS_STATES } from "shared-types";
import { useMemo } from "react";
 
const usePopulationData = (stateString: string) => {
  return useQuery(
    ["populationData", stateString],
    () =>
      fetch(
        `https://api.census.gov/data/2019/pep/population?get=NAME&for=county:*&in=state:${stateString}`,
      )
        .then((response) => response.json())
        .then((population) => population.slice(1).map((item) => item[0])),
    {
      refetchOnWindowFocus: false,
      refetchOnReconnect: false,
      refetchOnMount: false,
    },
  );
};
 
export const useGetCounties = (): { label: string; value: string }[] => {
  const { data: userData } = useGetUser();
 
  const stateCodes = useMemo(() => getUserStateCodes(userData?.user), [userData]);
 
  const stateNumericCodesString = useMemo(
    () =>
      stateCodes
        .map((code) => FULL_CENSUS_STATES.find((state) => state.value === code)?.code)
        .filter((code): code is string => code !== undefined && code !== "00")
        .join(","),
    [stateCodes],
  );
 
  const { data: populationData = [] } = usePopulationData(stateNumericCodesString);
 
  return (
    populationData.map((county) => {
      const [label] = county.split(",");
      return { label, value: county };
    }) ?? []
  );
};