Skip to content

Instantly share code, notes, and snippets.

@ashalfarhan
Created June 13, 2022 15:54
Show Gist options
  • Save ashalfarhan/975a039bbe6e00612416381ee8cebd95 to your computer and use it in GitHub Desktop.
Save ashalfarhan/975a039bbe6e00612416381ee8cebd95 to your computer and use it in GitHub Desktop.
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