Najam Us Saqib
Najam Us Saqib

Reputation: 3404

Getting Promise as return value inside FlatList React-native

Showing Values using react-native FlatList like:

<FlatList 
          data={this.state.oldLocations}
          showsVerticalScrollIndicator={false}
          keyExtractor={item => item.id}
          renderItem={({item,index}) =>
        <View key={index} style={styles.flatview}>
            <GoogleStaticMap
                latitude={item.latitude.toString()}
                longitude={item.longitude.toString()}
                zoom={13}
                size={{ width: 450 , height: 250 }}
                apiKey={'MY_API_KEY'}
            />

            <Text style={styles.name}>{item.id}</Text>
            <Text style={styles.email}>{item.latitude}</Text>
            <Text style={styles.email}>{item.longitude}</Text>
            {<Text style={styles.email}>{this.getAddress(item.latitude, item.longitude)})}</Text>}
          </View>

        }


        />

my Function getAddress inside FlatList returning promise. How can i show return values? my Func:

getAddress(lat, lng){

 return Geocoder.geocodePosition({lat: lat, lng: lng}).then(res => {
      // res is an Array of geocoding object (see below)
      console.log(res);
      return res[0].formattedAddress;
  })
  .catch(err => console.log(err))


}

Upvotes: 0

Views: 1578

Answers (1)

smashed-potatoes
smashed-potatoes

Reputation: 2222

Async calls cannot be returned and rendered as part of your render. Instead, you need to perform the async loading outside of the render and then set the retrieved data in the state for rendering.

In your case, you will need to have a stateful component that you used for each item in your FlatList. This component will handle loading and displaying the result once it is loaded.

e.g.:

class MapListItem extends React.Component {
  state = {
    address: '',
  }

  componentDidMount() {
    const {
      item,
    } = this.props;

    this.getAddress(item.latitude, item.longitude);
  }

  getAddress = (lat, lng) => {
    Geocoder.geocodePosition({lat: lat, lng: lng}).then(res => {
      this.setState({
        address: res[0].formattedAddress,
      });
    });
  }

  render() {
    return (
      // All your map/details - the other parts of your current renderItem
      ...
      <Text>{this.state.address}</Text>
      ...
    )
  }
}

And then your FlatList renderItem becomes:

renderItem={({ item, index }) => (
   <MapListItem item={item} index={index} />
)}

Upvotes: 3

Related Questions