Skip to content

Commit

Permalink
Add custom hook to fetch state and district from pincode
Browse files Browse the repository at this point in the history
  • Loading branch information
yash-learner committed Jan 6, 2025
1 parent bdd739f commit 6905db3
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions src/hooks/useStateAndDistrictFromPincode.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import careConfig from "@careConfig";
import { useQuery } from "@tanstack/react-query";

import { validatePincode } from "@/common/validation";

import { getPincodeDetails } from "@/Utils/utils";

import { useOrganization } from "./useOrganization";

interface UseStateAndDistrictProps {
pincode: string;
}

export function useStateAndDistrictFromPincode({
pincode,
}: UseStateAndDistrictProps) {
const {
data: pincodeDetails,
isLoading: isPincodeLoading,
isError: isPincodeError,
} = useQuery({
queryKey: ["pincode-details", pincode],
queryFn: () => getPincodeDetails(pincode, careConfig.govDataApiKey),
enabled: validatePincode(pincode),
});

const stateName = pincodeDetails?.statename || "";
const districtName = pincodeDetails?.districtname || "";

const {
organizations: stateOrgs,
isLoading: isStateLoading,
isError: isStateError,
} = useOrganization({
orgType: "govt",
parentId: "",
name: stateName,
enabled: !!stateName,
});

const stateOrg = stateOrgs?.[0];

const {
organizations: districtOrgs,
isLoading: isDistrictLoading,
isError: isDistrictError,
} = useOrganization({
orgType: "govt",
parentId: stateOrg?.id,
name: districtName,
enabled: !!stateOrg?.id && !!districtName,
});

const districtOrg = districtOrgs[0];

return {
stateOrg,
districtOrg,
isLoading: isPincodeLoading || isStateLoading || isDistrictLoading,
isError: isPincodeError || isStateError || isDistrictError,
};
}

0 comments on commit 6905db3

Please sign in to comment.