Created
September 16, 2023 19:04
-
-
Save josephdburdick/7fe98a672609cf7944896b9c4f3c84db to your computer and use it in GitHub Desktop.
Geolocation React 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 { useState, useEffect } from "react" | |
interface Coordinates { | |
latitude: number | |
longitude: number | |
} | |
interface GeoLocationError extends Error { | |
name: string | |
} | |
interface GeoLocationState { | |
coordinates: Coordinates | null | |
error: GeoLocationError | null | |
} | |
function useGeoLocation(): GeoLocationState { | |
const [state, setState] = useState<GeoLocationState>({ | |
coordinates: null, | |
error: null, | |
}) | |
useEffect(() => { | |
if (navigator.geolocation) { | |
navigator.geolocation.getCurrentPosition( | |
(position) => { | |
const { latitude, longitude } = position.coords | |
setState({ | |
coordinates: { latitude, longitude }, | |
error: null as unknown as GeoLocationError, | |
}) | |
}, | |
(error) => { | |
setState({ | |
coordinates: null, | |
error: error as unknown as GeoLocationError, | |
}) | |
} | |
) | |
} else { | |
setState({ | |
coordinates: null, | |
error: new Error("Geolocation not supported"), | |
}) | |
} | |
}, []) | |
return state | |
} | |
export default useGeoLocation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment