0

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),
      );
  }, []);
Darkshadowtrail
  • 208
  • 1
  • 10
  • how are you setting online state ? – Gaurav Roy Aug 29 '22 at 04:58
  • Does this answer your question? [React Native GeoLocation.watchPosition() using Initial value of state in success callback](https://stackoverflow.com/questions/72061993/react-native-geolocation-watchposition-using-initial-value-of-state-in-success) – Abe Aug 29 '22 at 06:39

0 Answers0