Skip to content

fix: ssr issue, move fns inside useEffect #2630

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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