Skip to content

Instantly share code, notes, and snippets.

@josephdburdick
Created September 16, 2023 19:04
Show Gist options
  • Save josephdburdick/7fe98a672609cf7944896b9c4f3c84db to your computer and use it in GitHub Desktop.
Save josephdburdick/7fe98a672609cf7944896b9c4f3c84db to your computer and use it in GitHub Desktop.
Geolocation React Hook
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