I want to calculate speed in my gps app, to do that I use states to save my current ans previous time, latitude and longitude. I initialize the subscribe function in useEffect, however the previous state of time, lat and lon is always the same even though it should be updated several times. How can I make this work without using localStorage to hold these values?
const [lat, setLat] = useState(51.55);
const [lon, setLon] = useState(0);
const [prevLat, setPrevLat] = useState(0);
const [prevLon, setPrevLon] = useState(0);
const [time, setTime] = useState(new Date());
const [prevTime, setPrevTime] = useState(new Date());
useEffect(() => {
Geolocation.getCurrentPosition().then((resp) => {
setTime(resp.timestamp);
setLat(resp.coords.latitude)
setLon(resp.coords.longitude)
}).catch((error) => {
console.log('Error getting location', error);
})
const onSuccess = () => {
console.log('success')
}
const onError = () => {
console.log('error')
}
let watch = Geolocation.watchPosition(onSuccess, onError, { enableHighAccuracy: true });
watch.subscribe((data) => {
if (data && data.coords && data.coords.latitude && data.coords.longitude) {
setPrevLat(lat);
setPrevLon(lon);
setPrevTime(time);
setLat(data.coords.latitude);
setLon(data.coords.longitude);
setTime(data.timestamp);
//calculate speed
console.log(calculateSpeed(prevTime, prevLat, prevLon, data.timestamp, data.coords.latitude, data.coords.longitude));
} else {
alert(data.message, ' ', data.code)
}
});
}, [])
In other words 4th, 5th and 6th arguments of calculateSpeed are proper values, but prevTime, prevLon and prevLat are still accordingly: date when the app started to run, 0, 0