Created
April 11, 2023 10:13
-
-
Save tjinlag/9f5b5e7a82ca429963843c98b0ec6c1f to your computer and use it in GitHub Desktop.
React Custom Hook: useGeolocation
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" | |
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