0

I am trying to fetch latitiude and longitude on a button click and set it to TextInput. The issue with below code is the placeholder is always undefined.

I tried removing the value attribute, in that case the placeholder is visible but then I am unable to set the location. How can i make the placeholder visible till the location is fetched and then once location is fetched set the value to latitude.

I guess I m not using the setLatLong correctly. can we use useRef to set the values correctly.

<TextInput
  style={{
      borderBottomColor: "black",
      borderBottomWidth: 2,
      color: "black",
    }}
  placeholder={"Longitude"}
  placeholderTextColor="blue"
  editable={false}
  textAlign="left"
  ref={longRef}
  value={latLong["latitude"] + ""}
/>

complete code is as follows

import {
  Text,
  View,
  Button,
  TouchableOpacity,
  StyleSheet,
  TextInput,
} from "react-native";

import RNLocation from "react-native-location";

RNLocation.configure({ distanceFilter: null });

const getLocation = () => {
  let latRef = React.createRef();
  let longRef = React.createRef();
  let latitude;
  let longitude;

  let [latLong, setLatLong] = useState({});

  const subscribeLocation = () => {
    RNLocation.requestPermission({
      ios: "whenInUse", // or 'always'
      android: {
        detail: "coarse", // or 'fine'
        rationale: {
          title: "We need to access your location",
          message: "We use your location to show where you are on the map",
          buttonPositive: "OK",
          buttonNegative: "Cancel",
        },
      },
    })
      .then((granted) => {
        console.log("Permission Granted: " + granted);
      })
      .catch((err) => {
        console.log(err);
      });
  };
  subscribeLocation();

  const fetchLocation = () => {
    if (RNLocation.getCurrentPermission()) {
      RNLocation.getLatestLocation({
        timeout: 60000,
      }).then((location) => {
        **setLatLong(location)**
      });
    }
  };

  return (
    <View style={styles.container}>
      <View style={styles.locationContainer}>
        <TextInput
          style={{
            borderBottomColor: "black",
            borderBottomWidth: 2,
            color: "black",
          }}
          placeholder={"Latitude"}
          placeholderTextColor="blue"
          editable={false}
          textAlign="left"
          ref={latRef}
          // value={latitude}
          value={latLong["latitude"] + ""}
        />

        <TextInput
          style={{
            borderBottomColor: "black",
            borderBottomWidth: 2,
            color: "black",
          }}
          placeholder={"Longitude"}
          placeholderTextColor="blue"
          editable={false}
          textAlign="left"
          ref={longRef}
          //  value=''
          value={latLong["latitude"] + ""}
        />

        <View style={styles.touchButton}>
          <Button
            title="Get Location"
            color="red"
            onPress={async () => {
              console.log("Press");
              await fetchLocation();
              // loci  = await fetchLocation()
              // setLatLong(loci)
              // console.log("Locii set")
              // console.log("Lociiiiii " +loci["longitude"])
              // longRef = loci["longitude"]
              // latRef = loci["latitude"]
            }}
          />
        </View>
      </View>

      <View style={styles.editIdContiner}>
        <View style={styles.touchButton}>
          <Button
            title="Get CSP Details"
            color="red"
            onPress={() => {
              console.log("Hiii");
            }}
          />
        </View>
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    width: "100%",
    position: "absolute",
    left: 0,
    top: 0,
    bottom: 0,
    flexDirection: "column",
    alignItems: "center",
    justifyContent: "space-evenly",
  },

  locationContainer: {
    width: "100%",
    flex: 1,
    backgroundColor: "yellow",
    justifyContent: "space-evenly",
    alignContent: "center",
  },

  editIdContiner: {
    width: "100%",
    flex: 1,
    backgroundColor: "red",
    justifyContent: "space-evenly",
    alignContent: "center",
  },

  touchButton: {
    width: "100%",
    color: "grey",
    alignItems: "center",
  },
});

export default getLocation;
7
  • 1
    what does the reponse look like inside fetchLocation?? Is it an object or a string?? I am talking about the location variable inside fetchLocation function Commented Apr 25, 2021 at 13:19
  • Try to console.log(location) before setLatLong(location) Commented Apr 25, 2021 at 13:21
  • According to your implementation.. Your response or I should say location should look like this ---> { latitude: "some data", longitude: ''some data here" } Commented Apr 25, 2021 at 13:26
  • Check out this Snack to see how to update the value in the field after performing fetch request. Commented Apr 25, 2021 at 13:28
  • @KartikeyVaish response is object with latitude and longitude Commented Apr 25, 2021 at 13:32

1 Answer 1

1

So the main approach is that..

According to the state variable. The Value should always be an Object containing two key-value pairs as shown below

Example Response -

{
   'latitude': "some value",
   'longitude': "some value",
{

This is because the value prop provided to the TextInput component displays latLong["latitude"] + ''. So, if we don't pass a correct object in the state..It will show undefined.

So whenever you fetch something then if you want to update the state then you must ensure that the response is of the above type..

This snack shows how to update the TextField value after fetching it from the server.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.