-
Notifications
You must be signed in to change notification settings - Fork 524
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add custom hook to fetch state and district from pincode
- Loading branch information
1 parent
bdd739f
commit 6905db3
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}; | ||
} |