Skip to content

Instantly share code, notes, and snippets.

@dejurin
Created October 16, 2023 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dejurin/afff7371dc540a7ea6802bb77a359a4b to your computer and use it in GitHub Desktop.
Save dejurin/afff7371dc540a7ea6802bb77a359a4b to your computer and use it in GitHub Desktop.
Hook
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