Created
April 8, 2023 17:21
-
-
Save ali-sabry/5880a1702636349dc58d6e9becd4264b to your computer and use it in GitHub Desktop.
This custom hook will allows you to get the user's current location, which can be useful for location-based features in your app, without any third part library.
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'; | |
const useGeolocation = () => { | |
const [location, setLocation] = useState({ | |
loaded: false, | |
coordinates: { latitude: '', longitude: '' }, | |
}); | |
const onSuccess = (location) => { | |
setLocation({ | |
loaded: true, | |
coordinates: { | |
latitude: location.coords.latitude, | |
longitude: location.coords.longitude, | |
}, | |
}); | |
}; | |
const onError = (error) => { | |
setLocation({ | |
loaded: true, | |
error, | |
}); | |
}; | |
useEffect(() => { | |
if (!('geolocation' in navigator)) { | |
onError({ | |
code: 0, | |
message: 'Geolocation not supported', | |
}); | |
} | |
navigator.geolocation.getCurrentPosition(onSuccess, onError); | |
}, []); | |
return location; | |
}; | |
//==== Usage | |
const App = () => { | |
const { loaded, coordinates, error } = useGeolocation(); | |
const { latitude, longitude } = coordinates; | |
const [country, setCountry] = useState(''); | |
useEffect(() => { | |
const url = | |
`https://api.bigdatacloud.net/data/reverse-geocode-client?latitude=${latitude}&longitude=${longitude}&localityLanguage=en`; | |
fetch(url) | |
.then(response => response.json()) | |
.then(data => setCountry(data.countryName)) | |
.catch(error => console.error(error)); | |
}, [latitude, longitude]); | |
if (error) <div>Error: {error.message}</div>; | |
if (!loaded) <div>Loading...</div>; | |
return <div>Country: {country} </div> //=== Egypt | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Made some adjustments
geolocation
in navigator the line where yougetCurrentPosition
will fail so i put it in the elseloading
instead ofloaded
location.coords
looks similar tocoordinates
so no need to break it down.location
tostate
. You are definiting the state of the hook not "location" data