Sign in
Log inSign up

React-Native setState: current Location for async operations

Nino's photo
Nino
·Apr 22, 2018

I want to get the distance of my tasks, wich are objects with lat lng values. They are saved in my firebase database.

Now my problem is, that I am setting the users current location in componentWillMount, by setState. If I debug my App I can see the location is set. But when I call getDistance, because I want to know the distance of my task and the users current location, from my async task (firebase query) the state of the users current location is null.

I think this happens because the operations are not in the same context. So I tried to dig into redux but could not master this topic.

How could I solve this?

getDistance(latitude, longitude) {
        let c = geolib.getDistance(
          { latitude: { latitude }, longitude: { longitude } }, // strawa
          { latitude: this.state.latitude, longitude: this.state.longitude }, // sbg
          100,
          1
        );
        return c / 1000;
        //alert(c / 1000); // 25km
      }

      /*
          Get the Users current location
          iOS -> asks only one time for permission, so pay atention if disabled !!!
      */
      getCurrentLocation() {
        var loc;
        navigator.geolocation.getCurrentPosition(
          position => {
            console.log("Location Request - Position = " + position);
            this.setState({
              latitude: position.coords.latitude,
              longitude: position.coords.longitude
            });
          },
          error => this.setState({ error: error.message }),
          { enableHighAccuracy: false, timeout: 200000, maximumAge: 1000 }
        );
      }

      componentWillMount() {
        this.getCurrentLocation();
        this.listenForTasks(this.tasksRef);
      }

    listenForTasks(tasksRef) {
    tasksRef.on("value", snap => {
      var tasks = [];
      snap.forEach(child => {
        // If Task_Type = 0 getDistance
        var distance = "";
        if (child.val().type === "0") {
          distance = this.getDistance(child.val().lat, child.val().lng);
        } else {
          distance = "Online";
        }
        tasks.push({
          title: child.val().title,
          budget: child.val().budget,
          offersCount: child.val().offersCount,
          commentsCount: child.val().commentsCount,
          distance: distance
        });
      });
      tasks.reverse();
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(tasks)
      });
    });
    }