useEffect.dev
← Back to lessons

Lesson 12. Custom hooks to use the browser’s APIs 6. Exercise: Get the user’s geolocation

Geolocation API also offers a way to get the user’s location in real-time via the watchPosition method. Can you update our hook also to return the new location when it changes? Don’t forget to unsubscribe from updates when the component is unmounted.

Result
Click here to see the solution!

All you need to do is replace getCurrentPosition with watchPosition, since both functions have exactly the same API:

const useGeolocation = () => {
const [status, setStatus] = useState('pending')
const [latitude, setLatitude] = useState(undefined)
const [longitude, setLongitude] = useState(undefined)
useEffect(() => {
navigator.geolocation.watchPosition(
(res) => {
setStatus('success')
setLatitude(res.coords.latitude)
setLongitude(res.coords.longitude)
},
(err) => {
console.log(err)
setStatus('error')
}
)
return () => {
navigator.geolocation.clearWatch()
}
}, [])
return { status, latitude, longitude }
}