Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 7 additions & 12 deletions src/useGeolocation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,11 @@ const useGeolocation = (options?: PositionOptions): GeoLocationSensorState => {
latitude: null,
longitude: null,
speed: null,
timestamp: Date.now(),
timestamp: null,
});
let mounted = true;
let watchId: any;

const onEvent = (event: any) => {
if (mounted) {
useEffect(() => {
const onEvent = (event: any) => {
setState({
loading: false,
accuracy: event.coords.accuracy,
Expand All @@ -54,17 +52,14 @@ const useGeolocation = (options?: PositionOptions): GeoLocationSensorState => {
speed: event.coords.speed,
timestamp: event.timestamp,
});
}
};
const onEventError = (error: IGeolocationPositionError) =>
mounted && setState((oldState) => ({ ...oldState, loading: false, error }));
};
const onEventError = (error: IGeolocationPositionError) =>
setState((oldState) => ({ ...oldState, loading: false, error }));

useEffect(() => {
navigator.geolocation.getCurrentPosition(onEvent, onEventError, options);
watchId = navigator.geolocation.watchPosition(onEvent, onEventError, options);
let watchId = navigator.geolocation.watchPosition(onEvent, onEventError, options);

return () => {
mounted = false;
navigator.geolocation.clearWatch(watchId);
};
}, []);
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ideally, options should be added in the deps array but the changes the behavior of the hook

Expand Down