I have been trying to debug this for hours now but to no avail. I wrote this script that basically when the component loads fetch information from my Firestore database. I then log one item from the array to the console, resulting in undefined
. I don't understand why it can show me the full array but not one item. And then the entire Array resulting in the full array (partial image seen below).
The main goal of this component is to produce a list of the items as seen in the list component but nothing is shown. My first guess is that method for getting information from the database is asynchronous, but would this matter if the state is updated? Shouldn't the app re-render?
Here is a snippet of my code, and help would be greatly appreciated!
export default class ItemScreen extends Component {
constructor () {
super()
this.state = {
items: [],
}
}
componentDidMount() {
var items = []
firebase.firestore().collection("items").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
items.push(doc.data());
});
})
this.setState({items: items});
console.log(items[1])
console.log(items)
}
render() {
const { items } = this.state
return (
<View style={styles.container}>
<SearchBar
lightTheme
onChangeText={(text) => console.log(text)}
onClearText={() => console.log("cleared")}
placeholder='Type Here...'
containerStyle={{width: "100%"}}
/>
<List containerStyle={{width: "100%"}}>
{
items.map((l) => (
<ListItem
roundAvatar
avatar={{uri:l.image}}
key={l.name}
title={l.name}
/>
))
}
</List>
</View>
);
}
}
Try restructuring to something more like
var items = []
var self = this;
firebase.firestore().collection("items").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
items.push(doc.data());
});
self.setState({items: items});
console.log(items[1])
console.log(items)
})
The code at the bottom of your original method would run before the results are available.
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.