Problems with watchPosition react native expo

Viewed 53

I want to send the user's position when I change location, but it does not work for me. I have tried with other code that I have found on this platform, but my attempts at converting that result in spaghetti code. I am cleaning it up and this is my code:

const get_user_id = await AsyncStorage.getItem('user_id');
      this.setState({ 
        user_id: get_user_id,
      });
      navigator.geolocation.watchPosition(
        position => {
          const locationLat = JSON.stringify(position.coords.latitude);
          const locationLong = JSON.stringify(position.coords.longitude);

          this.setState({ 
            lat: locationLat,
            long: locationLong,
          });
          
          fetch(confg.url+'guardaralerta', {
            method: 'POST',
            headers: {
              Accept: 'application/json',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              user_id: this.state.user_id,
              lat: this.state.lat,
              long: this.state.long,
            })
          }).then((response) => response.json())
          .then((responseData) => {
              console.log(JSON.stringify(responseData))  
          });
        },
        error => Alert.alert(error.message),
        { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
      );
  } catch (error) {
    console.log(error)    
  }
0 Answers
Related