In my React Native app I have a Geolocation.watchPosition
handler that I want to conditionally run whenever the app is open. However, the success function seems to take the state values that exist when the handler is invoked and doesn't call a new function with updated states when the position is changed. This leads to an axios request never being made.
For some reason, "Location changed offline!" is the only thing being logged. When I tried logging the state in every success call, false
is logged every time, despite the state being true when logged by a dummy TouchableOpacity
.
My code is below, how can I get the axios request to run only if the online state is true?
const [online, setOnline] = useState(false);
useEffect(() => {
Geolocation.watchPosition(
position => {
if(online) {
const payload = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
axios
.post('http://ip:3000/location/update', payload)
.then(res => {
if (res.status === 200) {
console.log('Location updated in real-time!\n');
}
})
} else {
console.log('Location changed offline!');
}
},
err => console.log(err.response),
);
}, []);