Created
March 6, 2021 14:33
-
-
Save lsbyerley/7d0c01cd7f2a892f3f8e7dcc80993760 to your computer and use it in GitHub Desktop.
useLocation React Hook
This file contains hidden or 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"; | |
const useCurrentLocation = (options = {}) => { | |
// store location in state | |
const [location, setLocation] = useState(); | |
// store error message in state | |
const [error, setError] = useState(); | |
// Success handler for geolocation's `getCurrentPosition` method | |
const handleSuccess = (pos) => { | |
const { latitude, longitude } = pos.coords; | |
setLocation({ | |
latitude, | |
longitude, | |
}); | |
}; | |
// Error handler for geolocation's `getCurrentPosition` method | |
const handleError = (error) => { | |
setError(error.message); | |
}; | |
useEffect(() => { | |
const { geolocation } = navigator; | |
// If the geolocation is not defined in the used browser we handle it as an error | |
if (!geolocation) { | |
setError("Geolocation is not supported."); | |
return; | |
} | |
// Call Geolocation API | |
geolocation.getCurrentPosition(handleSuccess, handleError, options); | |
}, [options]); | |
return { location, error }; | |
}; | |
export default useCurrentLocation; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment