Created
June 13, 2022 15:54
-
-
Save ashalfarhan/975a039bbe6e00612416381ee8cebd95 to your computer and use it in GitHub Desktop.
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 { useEffect, useRef, useState } from 'react'; | |
type GeoState = | |
| { | |
status: 'idle'; | |
} | |
| { | |
status: 'success'; | |
state: GeolocationPosition; | |
} | |
| { | |
status: 'error'; | |
error: GeolocationPositionError; | |
}; | |
export const useGeoLocation = (options: PositionOptions = {}) => { | |
const [state, setState] = useState<GeoState>({ status: 'idle' }); | |
const watchId = useRef<number>(); | |
useEffect(() => { | |
const onSuccess: PositionCallback = res => { | |
setState(prev => ({ | |
...prev, | |
status: 'success', | |
state: res, | |
error: null, | |
})); | |
}; | |
const onError: PositionErrorCallback = err => { | |
setState(prev => ({ | |
...prev, | |
status: 'error', | |
error: err, | |
state: null, | |
})); | |
}; | |
watchId.current = navigator.geolocation.watchPosition( | |
onSuccess, | |
onError, | |
options, | |
); | |
return () => { | |
if (watchId.current) { | |
navigator.geolocation.clearWatch(watchId.current); | |
} | |
}; | |
}, []); | |
return state; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment