Created
June 15, 2023 11:00
-
-
Save martinratinaud/8750f85c666d09cb77d250a69ba628da to your computer and use it in GitHub Desktop.
GeoData provider and hook for React
This file contains hidden or 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
import type { AppProps } from 'next/app'; | |
import React from 'react'; | |
import { useToggle } from 'react-use'; | |
export const GeoDataContext = React.createContext({ | |
geoData: undefined as GeoData | undefined, | |
}); | |
export interface GeoData { | |
ip: string; | |
network: string; | |
version: string; | |
city: string; | |
region: string; | |
region_code: string; | |
country: string; | |
country_name: string; | |
country_code: string; | |
country_code_iso3: string; | |
country_capital: string; | |
country_tld: string; | |
continent_code: string; | |
in_eu: boolean; | |
postal: null; | |
latitude: number; | |
longitude: number; | |
timezone: string; | |
utc_offset: string; | |
country_calling_code: string; | |
currency: string; | |
currency_name: string; | |
languages: string; | |
country_area: number; | |
country_population: number; | |
asn: string; | |
org: string; | |
} | |
export default function GeoDataProvider({ children }: AppProps['pageProps'] & any) { | |
const [loading, setLoading] = useToggle(false); | |
const [geoData, setGeoData] = React.useState<GeoData | undefined>(); | |
React.useEffect(() => { | |
if (loading || geoData) { | |
return; | |
} | |
setLoading(true); | |
const fetchCountry = async () => { | |
try { | |
const response = await fetch('https://ipapi.co/json/'); | |
const data: GeoData = await response.json(); | |
setGeoData(data); | |
} catch (error) { | |
console.error('Error fetching geo:', error); | |
} | |
setLoading(false); | |
}; | |
fetchCountry(); | |
}, [geoData, loading]); | |
return <GeoDataContext.Provider value={{ geoData }}>{children}</GeoDataContext.Provider>; | |
} |
This file contains hidden or 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
import { useContext } from 'react'; | |
import { GeoDataContext } from '../providers/GeoDataProvider'; | |
export default () => useContext(GeoDataContext); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment