Home > database >  UseEffect with getPermissionAsync
UseEffect with getPermissionAsync

Time:03-11

unfortunately I am struggling with the hook lifecycle in react native. I have two hooks at the top level.

const permission = useLocationPermission();
const location = useCurrentLocation(locationPermission);

The first one handles the location permission permission and asks the user to grand.

export default function useLocationPermission() {
  const [hasLocationPermission, setHasLocationPermission] = useState(false);
  const appState = useRef(AppState.currentState);

  useEffect(() => {
    
    hasPermission();
  }, []);

  const hasPermission = async () => {
    const { granted } = await Location.getForegroundPermissionsAsync();
    if (!granted) {
      const { granted: request } =
        await Location.requestForegroundPermissionsAsync();
      if (!request) {
        Alert.alert(
          "Some Message"
        );
        setHasLocationPermission(false);
      } else {
        setHasLocationPermission(true);
      }
    } else {
      setHasLocationPermission(true);
    }
  };
  
  return hasLocationPermission;
}

The second one handles the current location.

export default function useCurrentLocation(hasPermission: boolean) {
  const [currentLocation, setCurrentLocation] = useState<LatLng>(initLocation);

  useEffect(() => {
    console.log(hasPermission);

    if (hasPermission) {
      setWatcher();
      
      getCurrentPosition().then((locationObject) => {
        setCurrentLocation({
          latitude: locationObject.coords.latitude,
          longitude: locationObject.coords.longitude,
        });
      });
    } else {
      setCurrentLocation(initLocation);
    }
  }, []);

  const getCurrentPosition = async () => {
    return Location.getCurrentPositionAsync({});
  };

  const setWatcher = async () => {
    await Location.watchPositionAsync({ distanceInterval: 5 }, (locaction) => {
      setCurrentLocation({
        latitude: locaction.coords.latitude,
        longitude: locaction.coords.longitude,
      });
    });
  };
  return currentLocation;
}

My problem is that after the user has granted the permission. The location will not been updated anymore (still the initial location). It seems that the second hook is only called ones. Is there any best practice to handle such situation. So the location will be updated and the watcher is set after the permission is set.

Thanks a lot.

CodePudding user response:

Your list of dependencies for the effect that sets current location is empty. Since you are saying you want that effect to be dependant on hasPermission, set it to [hasPermission] instead.

  • Related