Created
October 16, 2023 15:49
-
-
Save dejurin/afff7371dc540a7ea6802bb77a359a4b to your computer and use it in GitHub Desktop.
Hook
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
import React from 'react'; | |
import { useSessionStorage } from '@mantine/hooks'; | |
export interface CFTrace { | |
status: string; | |
country: string; | |
countryCode: string; | |
region: string; | |
regionName: string; | |
city: string; | |
zip: string; | |
lat: number; | |
lon: number; | |
timeZone: string; | |
isp: string; | |
org: string; | |
as: string; | |
query: string; | |
} | |
export default function useCFTrace(): CFTrace | undefined { | |
const [cfTrace, setCfTrace] = useSessionStorage<CFTrace | undefined>({ | |
key: 'ip-api-trace', | |
defaultValue: undefined, | |
getInitialValueInEffect: false, | |
}); | |
React.useEffect(() => { | |
if (!cfTrace) { | |
const fetchData = async () => { | |
const response = await fetch('http://ip-api.com/json/'); | |
if (!response.ok) { | |
const error = new Error('An error occurred while fetching the data.'); | |
throw error; | |
} | |
const jsonData = (await response.json()) as CFTrace; | |
setCfTrace(() => jsonData); | |
}; | |
fetchData() | |
// eslint-disable-next-line no-console | |
.catch(console.error); | |
} | |
}, [cfTrace, setCfTrace]); | |
return cfTrace; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment