Skip to content

Commit

Permalink
feat: add error and loading fields to useGeolocation
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich authored Feb 19, 2019
2 parents 15771ef + dcadfef commit 6909a69
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/useGeolocation.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
import {useState, useEffect} from 'react';

export interface GeoLocationSensorState {
loading: boolean,
accuracy: number,
altitude: number,
altitudeAccuracy: number,
heading: number,
latitude: number,
longitude: number,
speed: number,
timestamp: number
timestamp: number,
error?: Error | PositionError
}

const useGeolocation = () => {
const [state, setState] = useState({
loading: true,
accuracy: null,
altitude: null,
altitudeAccuracy: null,
Expand All @@ -28,6 +31,7 @@ const useGeolocation = () => {
const onEvent = (event: any) => {
if (mounted) {
setState({
loading: false,
accuracy: event.coords.accuracy,
altitude: event.coords.altitude,
altitudeAccuracy: event.coords.altitudeAccuracy,
Expand All @@ -39,10 +43,12 @@ const useGeolocation = () => {
});
}
};
const onEventError = (error: any) =>
mounted && setState(oldState => ({...oldState, loading: false, error}));

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

return () => {
mounted = false;
Expand Down

0 comments on commit 6909a69

Please sign in to comment.