Created
July 27, 2021 10:54
-
-
Save codemile/562cd8880ccfd694b71cde0c6c79addb to your computer and use it in GitHub Desktop.
Hook for watching the users current location as geo coordinates.
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 {useEffect, useState} from 'react'; | |
const useGeoLocation = (options?: PositionOptions) => { | |
const [geo, setGeo] = useState<GeolocationPosition>(); | |
const [err, setError] = useState<GeolocationPositionError>(); | |
useEffect(() => { | |
const id = navigator.geolocation.watchPosition( | |
(pos) => { | |
setGeo(pos); | |
err && setError(undefined); | |
}, | |
(err) => setError(err), | |
options | |
); | |
return () => navigator.geolocation.clearWatch(id); | |
}, [err, options]); | |
return [geo, err]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment