Reputation: 231
enter image description here]1rybody
I am building a location based component need to take the city name to pass it through a get request for API to be like this
axios.get(/${cityName}/JSON
);
in the component I am writing some times working well but most of the time is giving that error ( null is not an object (evaluating 'location.coords')] )
How to get over that and how to get the cityName alone using latitude and longitude or whatever any other method
import React, { useState, useEffect } from 'react';
import { Platform, Text, View, Button } from 'react-native';
import Constants from 'expo-constants';
import * as Location from 'expo-location';
export default function App() {
const [location, setLocation] = useState(null);
const [errorMsg, setErrorMsg] = useState(null);
const [city, setCity] = useState('');
const getLocation = async () => {
let { status } = await Location.requestPermissionsAsync();
if (status !== 'granted') {
setErrorMsg('Permission to access location was denied');
}
let location = await Location.getCurrentPositionAsync({});
setLocation(location);
console.log(location);
}
const getCity = async () => {
const place = await Location.reverseGeocodeAsync({
latitude : location.coords.latitude,
longitude : location.coords.longitude
});
setCity(place.city);
console.log(city);
}
useEffect(() => {
getLocation() , getCity();
} , []);
let text = 'Waiting..';
if (errorMsg) {
text = errorMsg;
} else if (location) {
text = JSON.stringify(location);
}
return (
<View >
<Text> </Text>
<Button title = 'press'
onPress = {getCity}
/>
</View>
);
}
Upvotes: 0
Views: 106
Reputation: 11
So, the issue is that you are calling getCity when the component is first redered here without having the location object:
useEffect(() => {
getLocation() , getCity();
} , []);
Both functions are async, but that is not a guarantee that they will happen in that order. Moreover, what happens is that the functions run in parallel and that leads to your error.
You have multiple options here: - you can chain together multiple promises to ensure order of execution - you can remove the getCity call from the above useEffect and call it only after the getLocation call is done (do not allow the user to Interact before that)
Upvotes: 1