Skip to content

Instantly share code, notes, and snippets.

@amElnagdy
Created April 26, 2020 19:48
Show Gist options
  • Save amElnagdy/9400a2482dcf98a69a120192818bc5f7 to your computer and use it in GitHub Desktop.
Save amElnagdy/9400a2482dcf98a69a120192818bc5f7 to your computer and use it in GitHub Desktop.
React reusable hook to get the user location
// To use it, import useLocation from useLocation and then const [lat, errorMessage] = useLocation();
import { useState, useEffect } from "react";
export default () => {
const [lat, setLat] = useState(null);
const [errorMessage, setErrorMessage] = useState("");
useEffect(() => {
window.navigator.geolocation.getCurrentPosition(
(position) => setLat(position.coords.latitude),
(err) => setErrorMessage(err.message)
);
}, []);
return [lat, errorMessage];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment