Files
starr-philproperties/src/hooks/useDetectedCountry.js
T

34 lines
923 B
JavaScript

import { useEffect, useState } from 'react'
const COUNTRY_API_URL = import.meta.env.VITE_COUNTRY_API_URL
const FALLBACK_COUNTRY = 'PH'
/**
* Detects the caller's ISO 3166-1 alpha-2 country code via VITE_COUNTRY_API_URL
* (defaults to the free hosted https://api.country.is — self-hostable at
* https://github.com/lineofflight/country). Falls back to FALLBACK_COUNTRY
* if the endpoint is unset, unreachable, or returns no country.
*/
export function useDetectedCountry() {
const [country, setCountry] = useState(FALLBACK_COUNTRY)
useEffect(() => {
if (!COUNTRY_API_URL) return
let cancelled = false
fetch(COUNTRY_API_URL)
.then((res) => (res.ok ? res.json() : Promise.reject(res.status)))
.then((data) => {
if (!cancelled && data?.country) setCountry(data.country)
})
.catch(() => {})
return () => {
cancelled = true
}
}, [])
return country
}