Reputation: 17
I have DATA from petData.js that get data from firestore
import firebase from '../fb';
import 'firebase/firestore';
const DATA = [];
firebase
.firestore()
.collection('pets')
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
DATA.push(doc.data());
});
});
module.exports = DATA;
And Popular.js to wait for data before running
import DATA from '../data/petData';
class Popular extends Component {
render() {
return (
<View style={styles.container}>
<FlatList
data={DATA}
renderItem={item => {
return (
<PetItem
navigation={this.props.screenProps}
source={item.item.source}
name={item.item.name}
info={item.item.info}
price={item.item.price}
/>
);
}}></FlatList>
</View>
);
}
}
If i run before getting all data it become like this
Upvotes: 0
Views: 564
Reputation: 827
Yeah, u should take a look to lifecycle methods in react, in your case the render method it's run the first one and every time u set a state, so u should get the data in didMount method that's run after ur component mounted
So expected behavior at first time Data is null/undefined/empty so the flatlist will not appear
So u should put a get data function inside a componentDidMount()
//Popular.js
import firebase from '../fb';
import 'firebase/firestore';
class Popular extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
loading:true
}
}
ComponentDidMount(){
firebase
.firestore()
.collection('pets')
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
//DATA.push(doc.data());
this.setState({data:doc.data(), loading:false})
});
});
}
render() {
//make a loading component that appears if the data is empty
If(this.state.loading){
return(
<ActivityIndecator size="large" />
)else{
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
renderItem={item => {
return (
<PetItem
navigation={this.props.screenProps}
source={item.item.source}
name={item.item.name}
info={item.item.info}
price={item.item.price}
/>
);
}}
/>
</View>
);
}
}
}
Upvotes: 1