Issue setting unsubscribe from react-native-location to state variable

Viewed 550

I am having an issue with assigning a function using useState. From what I understand looking at the react-native-location documentation: https://github.com/timfpark/react-native-location

I am trying to use this bit from the documentation:

Subscribe
const unsubscribe = RNLocation.subscribeToLocationUpdates(locations => {
  ...
})

Unsubscribe
unsubscribe();

Now my issue is that I am trying to assign unsubscribe using the useState hook, so I can call it in my useEffect when a boolean returns false. So every time I try doing this it appears to hang the subscribeToLocationUpdates call itself so I never end up receiving the location objects that should get emited.

My Code:

My own hook for tracking users location:

useLocation.js

import {useState, useEffect} from 'react';
import RNLocation from 'react-native-location';

export default (shouldTrack, callback) => {
  const [error, setError] = useState('');
  const [unsubscribe, setUnsubscribe] = useState(null);

  RNLocation.configure({
    distanceFilter: 10, // Meters
    desiredAccuracy: {
      ios: 'bestForNavigation',
      android: 'balancedPowerAccuracy',
    },
    // Android only
    androidProvider: 'auto',
    interval: 5000, // Milliseconds
    fastestInterval: 10000, // Milliseconds
    maxWaitTime: 5000, // Milliseconds
    // iOS Only
    activityType: 'other',
    allowsBackgroundLocationUpdates: false,
    headingFilter: 1, // Degrees
    headingOrientation: 'portrait',
    pausesLocationUpdatesAutomatically: false,
    showsBackgroundLocationIndicator: false,
  });

  async function locationFetch() {
    await RNLocation.requestPermission({
      ios: 'whenInUse',
      android: {
        detail: 'fine',
        rationale: {
          title: 'Why do you need my location?',
          message: 'Im not creeping',
          buttonPositive: 'I understand',
          buttonNegative: 'Nope',
        },
      },
    })
      .then((granted) => {
        if (granted) {
          setError('');
          const unsub = RNLocation.subscribeToLocationUpdates(callback);
          setUnsubscribe(unsub);
        } else {
          throw new Error('Not Granted Locations Permissions');
        }
      })
      .catch((err) => {
        setError(err);
      });
  }

  useEffect(() => {
    if (shouldTrack) {
      locationFetch();
    } else {
      unsubscribe();
    }
  }, [shouldTrack]);

  return [error];
};

file where I use the hook:

import React, {useContext} from 'react';
//import {StyleSheet} from 'react-native';
import {Text} from 'react-native-elements';
import {SafeAreaView, withNavigationFocus} from 'react-navigation';
import Map from '../components/Map';
import {Context as LocationContext} from '../context/LocationContext';
import useLocation from '../hooks/useLocation';

const TrackCreateScreen = ({isFocused}) => {
  const {addLocation} = useContext(LocationContext);

  const [error] = useLocation(isFocused, addLocation);

  return (
    <SafeAreaView forceInset={{top: 'always'}}>
      <Text h2>Create a Track</Text>
      <Map />
      {error !== '' ? <Text>Please enable location services</Text> : null}
    </SafeAreaView>
  );
};

//const styles = StyleSheet.create({});

export default withNavigationFocus(TrackCreateScreen);

If you take out my setSubscribe it does begin emiting the events from the call, but then I can't call the unsubscribe method later.

Any help would be appreciated!

1 Answers

Hey Did you figure out this issue? It seems if you set state as a value to an object like in your case Instead of what you did

const unsub = RNLocation.subscribeToLocationUpdates(callback);
          setUnsubscribe(unsub);

Do this

const unsub = RNLocation.subscribeToLocationUpdates(callback);
          setUnsubscribe({'unsub':unsub});

Then you can call below to unsubscribe.

unsubscriber.unsub()

Dont know why it works, heck to me it doesnt even make sense. But it works and you can try it if you dont believe me.

edit: It kind of makes sense to me actually lol

Related