Created
November 1, 2018 16:18
-
-
Save ryanflorence/2c3d2b6e80430e3583ef7f03d17d69dc to your computer and use it in GitHub Desktop.
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"; | |
import { createResource } from "react-cache"; | |
let GeopositionResource = createResource(() => | |
new Promise((res, rej) => | |
navigator.geolocation.getCurrentPosition( | |
position => res(position), | |
error => rej(error) | |
) | |
) | |
); | |
let useGeoposition = () => { | |
let initialPosition = GeopositionResource.read(); | |
let [position, setPosition] = useState(initialPosition); | |
useEffect(() => { | |
let watchId = navigator.geolocation.watchPosition(setPosition); | |
return () => navigator.geolocation.clearWatch(watchId); | |
}, []); | |
return position; | |
}; | |
export default useGeoposition; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment