I get my data from firebase, push the data into an array and render the items in flatlist component. What did i miss?
but list render the items only for a really short time.
import React, { useState, useEffect } from 'react';
import { FlatList, Box } from "native-base";
import { StyleSheet } from 'react-native'
import EventCard from "./EventCard.js";
import { LogBox } from 'react-native';
import { ActivityIndicator } from 'react-native';
import { getFirestore, collection, getDocs } from 'firebase/firestore';
// Silent warning about https://github.com/facebook/react-native/issues/12981
LogBox.ignoreLogs(['Setting a timer']);
export default function Events() {
const [loading, setLoading] = useState(true);
const [events, setEvents] = useState({});
useEffect(() => {
let eventData = []
const firestore = getFirestore();
const querySnapshot = getDocs(collection(firestore, 'events'));
querySnapshot.then(querySnapshot => {
querySnapshot.docs.map(doc => {
eventData.push(doc.data())
setEvents(eventData)
})
});
setLoading(false);
}, []);
if (loading) {
return <ActivityIndicator />;
}
return (
<Box style={styles.container}>
<FlatList
data={events}
keyExtractor={item => item.key}
renderItem={({ item }) => (<EventCard key={Date.now()} eventData={item} />
)}
/>
</Box>
);
}
const styles = StyleSheet.create({
container: {
alignSelf: 'stretch',
alignItems: 'center'
},
})
Thanks for your time. i really stuck.
CodePudding user response:
You have setEvents(eventData)
in the map()
so after every iteration the state is being updated. Instead parse the data and then update state once.
querySnapshot.then(querySnapshot => {
querySnapshot.docs.map(doc => {
eventData.push(doc.data())
})
// After iterating over all docs
setEvents(eventData)
});