Skip to content

Instantly share code, notes, and snippets.

@tjinlag
Created April 11, 2023 10:13
Show Gist options
  • Save tjinlag/9f5b5e7a82ca429963843c98b0ec6c1f to your computer and use it in GitHub Desktop.
Save tjinlag/9f5b5e7a82ca429963843c98b0ec6c1f to your computer and use it in GitHub Desktop.
React Custom Hook: useGeolocation
import { useState, useEffect } from "react"
export default function useGeolocation(options) {
const [loading, setLoading] = useState(true)
const [error, setError] = useState()
const [data, setData] = useState({})
useEffect(() => {
const successHandler = e => {
setLoading(false)
setError(null)
setData(e.coords)
}
const errorHandler = e => {
setError(e)
setLoading(false)
}
navigator.geolocation.getCurrentPosition(
successHandler,
errorHandler,
options
)
const id = navigator.geolocation.watchPosition(
successHandler,
errorHandler,
options
)
return () => navigator.geolocation.clearWatch(id)
}, [options])
return { loading, error, data }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment