1

Need help converting RNLocation.requestPermission and _startUpdatingLocation to work with function components in react native.

Not sure how to approach this

LatLon Component File

import React, {useState} from "react";
import { SafeAreaView, StyleSheet, Text, } from "react-native";
import RNLocation from "react-native-location";
import moment from "moment";
import styled from 'styled-components/native';

function LatLonBox(){

  const [currentLocation, setLocation] = useState(null);

  const styles = StyleSheet.create({
    Custom_Text:{
      textAlign:'center',
      fontSize:15
  }
  });

  const LocationContainer = styled.View`
    marginTop: 10;
    marginBottom: 10;
  `;


  //How to make this work in functional style component
  RNLocation.requestPermission({
    ios: "whenInUse"
    }).then(granted => {
        if (granted) {
            this._startUpdatingLocation();
        }
    });
  }

  //How to make this work in functional style component
  _startUpdatingLocation = () => {
    this.locationSubscription = RNLocation.subscribeToLocationUpdates(
        locations => {
            this.setState({ location: locations[0] });
        }
    );
  };


  return(
    <SafeAreaView>
        <React.Fragment>
          <LocationContainer>
            <Text style = {styles.CustomText}>{currentLocation.longitude}</Text>
            <Text style = {styles.CustomText}>{currentLocation.latitude}</Text>
          </LocationContainer>
        </React.Fragment>
    </SafeAreaView>
  ); 
}

export default LatLonBox;

Screen File //Just extra if needed

import React from 'react';
import {  SafeAreaView } from 'react-native';
import { StackParamList } from '../types';
import { BottomSheetModalProvider } from '@gorhom/bottom-sheet';
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import LatLonBox from '../components/LatLonBox';

export default ({}: NativeStackScreenProps<StackParamList, 'Main'>): JSX.Element => {
  
  return (
    <BottomSheetModalProvider>
        <SafeAreaView style={{ flex: 1}}>
        <LatLonBox/>     //where LatLon will be placed   
      </SafeAreaView>
    </BottomSheetModalProvider>
  );
};

Link to RNLocation Library

bombombs
  • 593
  • 1
  • 13

1 Answers1

0

You can check this

Hey hope this helps, feel free for doubts:

  const _startUpdatingLocation = () => {
   const locationSubscription = RNLocation.subscribeToLocationUpdates(
        locations => {
           setLocation(locations[0])
        }
    );
  };

const requestPermission = useCallback(() => {

RNLocation.requestPermission({
    ios: "whenInUse"
    }).then(granted => {
        if (granted) {
            _startUpdatingLocation();
        }
    });
  }
  
},[_startUpdatingLocation])

useEffect(() => {
requestPermission()
},[requestPermission])

//How to make this work in functional style component
  

 
Gaurav Roy
  • 11,175
  • 3
  • 24
  • 45