Here is a function I am working with:
const [dataLoc, setDataLoc] = useState({date: "No data received yet from sensor", coords: {}});
This is where I set the location:
Geolocation.getCurrentPosition(
location => {
const date = dateToString(location.timestamp);
const coords = location.coords
setDataLoc({date, coords})
}
)
The coords interface looks like this:
export interface GeoCoordinates {
latitude: number;
longitude: number;
accuracy: number;
altitude: number | null;
heading: number | null;
speed: number | null;
altitudeAccuracy?: number | null;
}
Imported from:
import Geolocation from 'react-native-geolocation-service';
I am trying to render the data as follows:
<Text style={styles.data}>{dataLoc.coords.latitude}</Text>
However, I am encountering an error message that says:
error: SyntaxError: .../App.tsx: Unexpected token
I cannot access any properties of the object because it is empty {}
, as declared in useState()
.
Is there a way for me to add coordinates to dataLoc without explicitly defining them and still be able to retrieve the object elements or define values as numbers or null?
I have also attempted to define it in useState()
as:
const [dataLoc, setDataLoc] = useState({
date: "No data received yet from sensor",
coords: {
latitude: 0,
longitude: 0,
altitude: 0,
accuracy: 0,
altitudeAccuracy: 0,
heading: 0,
speed: 0
}
});
But then I receive the following error:
Type '{ latitude: number; longitude: number; altitude: number
| null; accuracy: number; altitudeAccuracy: number | null;
heading: number | null; speed: number | null; }' is not
assignable to type '{ latitude: number; longitude: number;
altitude: number; accuracy: number; altitudeAccuracy: number;
heading: number; speed: number; }'.
Types of property 'altitude' are incompatible.
Type 'number | null' is not assignable to type 'number'.
Type 'null' is not assignable to type 'number'.