I want to pick a "city" in the Picker and my Flatlist should display only restaurants from that city. So basically, if the user selects "city1" then the list should display only restaurants of that city.
Here is my current code, getRestaurants() function:
async getRestaurants() {
firebase.firestore().collection('restaurants').get().then(querySnapshot => {
const data = querySnapshot.docs.map(doc => doc.data());
this.setState({ dataRestaurants: data });
console.log("printing picked city", this.state.city);
if (this.state.city !== "all") {
for (let i = 0; i < this.state.dataRestaurants.length; i++) {
var arr = this.state.dataRestaurants[i];
var arrStrng = JSON.stringify(arr);
console.log("Looping through array of restaurants: " + arrStrng);
}
}
else {
for (let i = 0; i < this.state.dataRestaurants.length; i++) {
var arr = this.state.dataRestaurants[i];
var arrStrng = JSON.stringify(arr);
console.log("Looping through array of restaurants: " + arrStrng);
}
}
})
}
This is the rendering:
<View>
<View >
<Text style={styles.textStyle}>Picker Example</Text>
<Picker
selectedValue={this.state.city}
style={{ height: 50, width: 100 }}
onValueChange={(throttlemodeValue, throttlemodeIndex) =>
this.updateCity(throttlemodeValue)}
>
<Picker.Item label="All" value="all" />
<Picker.Item label="Prishtine" value="Prishtine" />
<Picker.Item label="Gjakove" value="Gjakove" />
<Picker.Item label="Prizren" value="Prizren" />
<Picker.Item label="Gjilan" value="Gjilan" />
</Picker>
<Text style={styles.textStyle}> {"City =" + this.state.city}</Text>
</View>
<View >
<FlatList
style={styles2.containerStyle}
keyExtractor={(item) => item.res_id}
data={this.state.dataRestaurants}
enableEmptySections={true}
renderItem={({ item }) => this.renderNativeItem(item)}
/>
</View>
</View>
Here is a link for Demo
Maintain a selected city variable in state.Update it with the picker onChange
, then from the changed state variable pick up the corresponding data from the state/props as
this.state.dataRestaurant[this.state.city]
Your flatlist looks like this.
<FlatList
style={styles.flatList}
keyExtractor={item => item.res_id}
data={this.state.dataRestaurants[this.state.city]}
enableEmptySections={true}
renderItem={({ item }) => this.renderNativeItem(item)}
/>