I have a flatlist that receives eventIds as data. On each renderItem call I want to find the corresponding event-object to each eventId on firebase and render this data. (E.g. title or image from this event)
This is the function to get a single event from firestore based on the eventId:
export async function getSingleEventDataFireStore(eventId) {
const db = firebase.firestore();
const eventFirestoreDoc = db.collection("events").doc(eventId);
const doc = await eventFirestoreDoc.get();
if (!doc.exists) {
console.log("No such Event!");
} else {
console.log("Event data fetched!");
return await doc.data();
}
}
this is where the flatlist is displayed:
const EventScreen = () => {
const [event, setEvent] = useState([]);
const [eventFetched, setEventFetched] = useState(false);
const eventIds = [{id:'1', eventId: 'jaelfmk130'}, {id:'2', eventId: '1jlk335n1'}]
const renderItem = ({ item }) => {
if (!eventFetched) {
firestore.getSingleEventDataFireStore(item.eventId).then((eventItem) => {
setEvent(eventItem);
setEventFetched(true);
});
}
setEventFetched(false)
return ( <View><Text>{event.title}</Text></View> )
}
return (
<View>
<FlatList
data={eventIds}
keyExtractor={(item) => item.id}
renderItem={renderItem}
/>
</View> )
}
This ends up in an infinite loop, because I set eventFetched to false again during renderItem. Otherwise, if I remove setEventFetched(false) it only renders one item.
How can I set eventFetched to false after the render of each item without ending up in a loop?