简体   繁体   中英

Push the value returned from a promise into an array

I have this basic google map api in react which just puts some markers on the map in componentDidMount. To do that I need to use Geocode in order to convert a location (Green Street, nr.11, New York) to a latitude, longitude pair. This part works fine and the code is bellow:

  componentDidMount() {
    let usersLocations = [];
    this.props.users.map(user => {
      const userAddress =
        "Street " + user.street + " " + user.nr + ", " + user.city;
      Geocode.fromAddress(userAddress).then(
        response => {
          const result = { user: user, coord: response.results[0] };
          userLocations.push(result);
        },
        error => {}
      );
    });
    console.log(usersLocations) //outputs []
  }

The thing is, if I setState directly into the callback from Geocode, I'm doing this multiple times since I'm iterating over the users from the props. What I thought was to push each location into an array and then setState once for the entire array. The problem is, I can't push the result into the array since I'm in the callback and by the time I get the response from geocode the usersLocations array has been logged to the console already. How should I approach this?

You need to use Promise.all to collect all the data before setting the state

componentDidMount() {
    Promise.all(this.props.users.map(user => {
      const userAddress =
        "Street " + user.street + " " + user.nr + ", " + user.city;
      return Geocode.fromAddress(userAddress).then(
        response => ({ user: user, coord: response.results[0]}),
        error => {}
      );
    })).then(usersLocations => this.setState({ usersLocations }));
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM