2

In the code example I am trying to call setState() with an array of Promise objects. The data (coordinates) have to be fetched from an external REST service.

Is there a common pattern for doing this in React?

   async getLocations(locations) {
     var annotations = locations.map(this.getLocation);
     console.log("ANNOTATIONS:", annotations);
     this.setState({
       annotations:annotations
     });
   }

   async getLocation(location) {
      try {
        let res = await Geocoder.geocodeAddress(location.address);
        return (
          {
              latitude: res[0].position.lat,
              longitude: res[0].position.lng,
              title: location.address,
              subtitle: location.provider,
          }
        );
      }
      catch(err) {
        console.log("Error fetching geodata",err);
      }
      return null;
  }

The resulting array contains Promise objects and the state update results in error:

ANNOTATIONS: [Promise, Promise, Promise, Promise, Promise, Promise, Promise]
ExceptionsManager.js:70 Warning: Failed prop type: Required prop `annotations[0].latitude` was not specified in `MapView`.
    in MapView (at index.js:204)
    in SampleAppInspection (at renderApplication.ios.js:90)
    in RCTView (at View.js:348)
    in View (at renderApplication.ios.js:65)
    in RCTView (at View.js:348)
    in View (at renderApplication.ios.js:64)
    in AppContainer (at renderApplication.ios.js:89)
Peter G.
  • 7,816
  • 20
  • 80
  • 154
  • Have a look at https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – Bergi Jul 05 '16 at 09:35

1 Answers1

2

This is actually pretty simple. You need to unwrap the array of promises you're passing setState since it is not promise aware:

 this.setState({
   annotations: await Promise.all(annotations)
 });

The Promise.all part waits for the entire array and the await unwraps it for setState.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504