Agontuk / react-native-geolocation-service

React native geolocation service for iOS and android
https://www.npmjs.com/package/react-native-geolocation-service
MIT License
1.61k stars 292 forks source link

watchPosition returning undefined #194

Closed mrousavy closed 4 years ago

mrousavy commented 4 years ago

Hi!

I'm using watchPosition to get frequent location changes.

I have created a react hook for this, but the location always stays undefined, the success callback is never called (neither is the Error callback).

import Geolocation from 'react-native-geolocation-service';
import { Coordinates } from '../interfaces/PostLocation';
import { useEffect, useState } from 'react';

export default function useCurrentLocationWatch(
    onError?: (error: Geolocation.GeoError) => void,
    options?: Geolocation.GeoWatchOptions,
): Coordinates | undefined {
    const [currentLocation, setCurrentLocation] = useState<Coordinates | undefined>();

    useEffect(() => {
        const watchID = Geolocation.watchPosition(
            (position) => {
                setCurrentLocation({
                    latitude: position.coords.latitude,
                    longitude: position.coords.longitude,
                });
            },
            onError,
            options,
        );

        return Geolocation.clearWatch(watchID);
    }, [onError, options]);

    return currentLocation;
}

Did I do something wrong?

Agontuk commented 4 years ago

You're calling the clearWatch immediately after watchPosition. I think it should be like this

return () => Geolocation.clearWatch(watchID);
mrousavy commented 4 years ago

@Agontuk wow. I should really get some sleep. Thanks 🙏