Skip to content

Instantly share code, notes, and snippets.

@ryanflorence
Created November 1, 2018 16:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanflorence/2c3d2b6e80430e3583ef7f03d17d69dc to your computer and use it in GitHub Desktop.
Save ryanflorence/2c3d2b6e80430e3583ef7f03d17d69dc to your computer and use it in GitHub Desktop.
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