Created
November 9, 2021 22:53
-
-
Save exaucae/d95fd124a8f07aeee61d6b72db562bd0 to your computer and use it in GitHub Desktop.
React hook that retrieves current user position
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 React, {useState} from 'react' | |
const useLocation = () => { | |
const initialState = { | |
latitude: '', | |
longitude: '', | |
error: '', | |
accuracy: '', | |
timestamp: '' | |
} | |
const [userCoordinates, setUserCoordinates] = useState(initialState); | |
function onSuccess(position) { | |
setUserCoordinates((prevState) => ({ | |
...prevState, | |
latitude: position.coords.latitude, | |
longitude: position.coords.longitude, | |
accuracy: position.coords.accuracy, | |
timestamp: position.timestamp, | |
})) | |
} | |
function onError() { | |
setUserCoordinates((prevState) => ({ | |
...prevState, | |
error: 'Geolocation is not supported by your browser', | |
})) | |
} | |
if (!navigator.geolocation) { | |
setUserCoordinates(() => ({ | |
...initialState, | |
error: 'Geolocation is not supported by your browser', | |
})) | |
} else { | |
navigator.geolocation.getCurrentPosition(onSuccess, onError); | |
} | |
return ( | |
{ | |
latitude: userCoordinates.latitude, | |
longitude: userCoordinates.longitude, | |
timestamp: userCoordinates.timestamp, | |
accuracy: userCoordinates.accuracy, | |
error: userCoordinates.error, | |
} | |
) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment